在JavaScript中2个日期之间有区别吗? [重复]

本文翻译自:Get difference between 2 dates in JavaScript? [duplicate]

This question already has answers here : 这个问题已经在这里有了答案
Closed 4 years ago . 4年前关闭。

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. 我尝试了上述方法,但这没有用。


#1楼

参考:https://stackoom.com/question/DWvS/在JavaScript中-个日期之间有区别吗-重复


#2楼

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. 该问题的先前答案并未解决两个日期跨越夏令时(DST)变化的情况。 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更改发生的日期的持续时间(以毫秒为单位)为!= 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. 这是因为UTC时间从不遵守DST。 See Does UTC observe daylight saving time? 请参阅UTC是否遵守夏令时?

ps 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. ps在讨论了有关此答案的一些评论之后,一旦您了解了跨越DST边界的javascript日期的问题,很可能不只一种解决方法。 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. 我很想知道是否有一个简单的基于算术/数学的解决方案,而不必实例化两个新的Date对象。 That could potentially be faster. 这可能会更快。


#3楼

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. 我使用了原始输入值,但是您没有指定格式,因此我假设第一个值是7月11日。 If it was intended to be November 7th, then adjust the format to D/M/YYYY instead. 如果计划在11月7日,则将格式调整为D/M/YYYY


#4楼

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 小提琴可以在这里看到DEMO


#5楼

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);

#6楼

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(diffDays);

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格式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值