在 JavaScript 中获取 2 个日期之间的差异?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3224834/
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-08-23 03:45:20  来源:igfitidea点击:

Get difference between 2 dates in JavaScript?

javascriptdate

提问by chobo2

How do I get the difference between 2 dates in full days (I don't want any fractions of a day)

我如何在全天中获得 2 个日期之间的差异(我不想要一天的任何部分)

var date1 = new Date('7/11/2010');
var date2 = new Date('12/12/2010');
var diffDays = date2.getDate() - date1.getDate(); 
alert(diffDays)

I tried the above but this did not work.

我尝试了上述方法,但这不起作用。

回答by TNi

Here is one way:

这是一种方法

const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
console.log(diffTime + " milliseconds");
console.log(diffDays + " days");

Observe that we need to enclose the date in quotes. The rest of the code gets the time difference in milliseconds and then divides to get the number of days. Date expects mm/dd/yyyy format.

请注意,我们需要将日期括在引号中。其余代码获取以毫秒为单位的时间差,然后除以获取天数。日期需要 mm/dd/yyyy 格式。

回答by Shyam Habarakada

A more correct solution

更正确的解决方案

... since dates naturally have time-zone information, which can span regions with different day light savings adjustments

...因为日期自然具有时区信息,可以跨越具有不同夏令时调整的区域

Previous answers to this question don't account for cases where the two dates in question span a daylight saving time (DST) change. The date on which the DST change happens will have a duration in milliseconds which is != 1000*60*60*24, so the typical calculation will fail.

此问题的先前答案未考虑所讨论的两个日期跨越夏令时 (DST) 更改的情况。DST 更改发生的日期将以毫秒为单位的持续时间为!= 1000*60*60*24,因此典型计算将失败。

You can work around this by first normalizing the two dates to UTC, and then calculating the difference between those two UTC dates.

您可以通过首先将两个日期标准化为 UTC,然后计算这两个 UTC 日期之间的差异来解决此问题。

Now, the solution can be written as,

现在,解决方案可以写成,

const _MS_PER_DAY = 1000 * 60 * 60 * 24;

// a and b are javascript Date objects
function dateDiffInDays(a, b) {
  // Discard the time and time-zone information.
  const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

  return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

// test it
const a = new Date("2017-01-01"),
    b = new Date("2017-07-25"),
    difference = dateDiffInDays(a, b);

This works because UTC time never observes DST. See Does UTC observe daylight saving time?

这是有效的,因为 UTC 时间从不观察 DST。请参阅UTC 是否遵守夏令时?

p.s. After discussing some of the comments on this answer, once you've understood the issues with javascript dates that span a DST boundary, there is likely more than just one way to solve it. What I provided above is a simple (and tested) solution. I'd be interested to know if there is a simple arithmetic/math based solution instead of having to instantiate the two new Date objects. That could potentially be faster.

ps 在讨论了有关此答案的一些评论之后,一旦您了解了跨越 DST 边界的 javascript 日期问题,解决它的方法可能不止一种。我上面提供的是一个简单(并经过测试)的解决方案。我很想知道是否有一个简单的基于算术/数学的解决方案,而不必实例化两个新的 Date 对象。这可能会更快。

回答by Matt Johnson-Pint

Here is a solution using moment.js:

这是使用moment.js的解决方案:

var a = moment('7/11/2010','M/D/YYYY');
var b = moment('12/12/2010','M/D/YYYY');
var diffDays = b.diff(a, 'days');
alert(diffDays);

I used your original input values, but you didn't specify the format so I assumed the first value was July 11th. If it was intended to be November 7th, then adjust the format to D/M/YYYYinstead.

我使用了您的原始输入值,但您没有指定格式,因此我假设第一个值是 7 月 11 日。如果原定为 11 月 7 日,则将格式调整为D/M/YYYY

回答by volkan er

var date1 = new Date("7/11/2010");
var date2 = new Date("8/11/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10); 

alert(diffDays )

回答by Mikeys4u

I tried lots of ways, and found that using datepicker was the best, but the date format causes problems with JavaScript....

我尝试了很多方法,发现使用 datepicker 是最好的,但是日期格式会导致 JavaScript 出现问题....

So here's my answer and can be run out of the box.

所以这是我的答案,可以开箱即用。

<input type="text" id="startdate">
<input type="text" id="enddate">
<input type="text" id="days">

<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {

$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end   = $('#enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
}); //end change function
}); //end ready
</script>

a Fiddle can be seen here DEMO

一个小提琴可以在这里看到演示

回答by Pec1983

This is the code to subtract one date from another. This example converts the dates to objects as the getTime() function won't work unless it's an Date object.

这是从另一个日期中减去一个日期的代码。此示例将日期转换为对象,因为除非它是 Date 对象,否则 getTime() 函数将不起作用。

    var dat1 = document.getElementById('inputDate').value;
                var date1 = new Date(dat1)//converts string to date object
                alert(date1);
                var dat2 = document.getElementById('inputFinishDate').value;
                var date2 = new Date(dat2)
                alert(date2);

                var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
                var diffDays = Math.abs((date1.getTime() - date2.getTime()) / (oneDay));
                alert(diffDays);