javascript 在javascript中将两个日期时间加在一起

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16240262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:51:16  来源:igfitidea点击:

Add two dates times together in javascript

javascriptdate

提问by Takwa Chammam

I am trying to add two dates:

我正在尝试添加两个日期:

date start Fri Apr 26 2013 16:08:03 GMT+0100 (Paris, Madrid)
+  
date periode Fri Apr 26 2013 00:10:00 GMT+0100 (Paris, Madrid)

I used this code:

我使用了这个代码:

var periode=$("#dure").val();
var start = $("#start").val()
var end =$("#end").val();

var dateStart= new Date(start);
console.log('start');
console.log(dateStart);

var date=dateStart.format('yyyy-mm-dd'); 
per=date+' '+periode;
var datePeriode= new Date(per);

console.log('datePeriode');
console.log(datePeriode);
var dateEnd= dateStart.getTime()+datePeriode.getTime();
console.log('dateEnd');
console.log(dateEnd);

In my JavaScript console, I get:

在我的 JavaScript 控制台中,我得到:

dateDebut
Fri Apr 26 2013 16:33:11 GMT+0100 (Paris, Madrid)
datePeriode
Fri Apr 26 2013 00:15:00 GMT+0100 (Paris, Madrid)
dateEnd
2733922091000

How can I fix that? Am I missing something?

我该如何解决?我错过了什么吗?

回答by Vivin Paliath

If you want to add a time period to a date, you basically have to convert both of them into milliseconds.

如果要为日期添加时间段,则基本上必须将它们都转换为毫秒。

var date = new Date();
var dateMillis = date.getTime();

//JavaScript doesn't have a "time period" object, so I'm assuming you get it as a string
var timePeriod = "00:15:00"; //I assume this is 15 minutes, so the format is HH:MM:SS

var parts = timePeriod.split(/:/);
var timePeriodMillis = (parseInt(parts[0], 10) * 60 * 60 * 1000) +
                       (parseInt(parts[1], 10) * 60 * 1000) + 
                       (parseInt(parts[2], 10) * 1000);

var newDate = new Date();
newDate.setTime(dateMillis + timePeriodMillis);

console.log(date); //eg: Fri Apr 26 2013 08:52:50 GMT-0700 (MST)
console.log(newDate); //eg: Fri Apr 26 2013 09:07:50 GMT-0700 (MST)

回答by Schleis

Convert datePeriod to milliseconds instead of making it into a date object for your addition.

将 datePeriod 转换为毫秒,而不是将其转换为用于添加的日期对象。

You need to convert the sum to a date. getTime()is in milliseconds since 1-1-1970. So you want to do.

您需要将总和转换为日期。 getTime()自 1-1-1970 以来的毫秒数。所以你想做。

var ending = new Date();
ending.setTime(dateEnd);
console.log(ending);

setTimewill set the date properly for you.

setTime将为您正确设置日期。

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setTime

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setTime