var date1 = new Date("7/13/2010");
var date2 = new Date("12/15/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
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);
<script>
function myFunction() {
var date1=new Date();// for current date
var date2 =new Date("Sep, 30, 2015");
// for other date you can get the another date from a textbox by
// var Newdate=document.getElementById('<%=textBox1.ClientID%>').value;
// convert Newdate to dateTime by...... var date2=New Date(Newdate);
var yearDiff=date1.getFullYear()-date2.getFullYear();// for year difference
var y1=date1.getFullYear();
var y2=date2.getFullYear();
var monthDiff=(date1.getMonth() + y1*12)-(date2.getMonth() +y2*12);
var day1=parseInt(date1.getDate());
var day2=parseInt(date2.getDate());
var dayDiff= (day1-day2)+ (monthDiff * 30);
document.write("Number of day difference : "+dayDiff);
}
</script>
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);
64
var date1 = new Date("7/11/2010");
var date2 = new Date("8/11/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24));
alert(diffDays )
7 回答
Here is one way:
请注意,我们需要将日期括在引号中 . 其余代码以毫秒为单位获取时间差,然后除以得到天数 . 日期需要mm / dd / yyyy格式 .
更正确的解决方案
...因为日期自然有时区信息,可以跨越具有不同日光节约调整的区域
此问题的先前答案不考虑有问题的两个日期跨越夏令时(DST)更改的情况 . DST更改发生的日期将以毫秒为单位,即
!= 1000*60*60*24
,因此典型计算将失败 .您可以通过首先将两个日期标准化为UTC,然后计算这两个UTC日期之间的差异来解决此问题 .
现在,解决方案可以写成,
这是因为UTC时间从不观察DST . 见Does UTC observe daylight saving time?
附:在讨论了关于这个答案的一些评论之后,一旦你有兴趣知道是否有一个简单的基于算术/数学的解决方案而不必实例化两个新的Date对象 . 这可能会更快 .
1000000%肯定...............
这是使用moment.js的解决方案:
我使用了您的原始输入值,但您没有指定格式,所以我假设第一个值是7月11日 . 如果打算在11月7日,那么请将格式调整为
D/M/YYYY
.我尝试了很多方法,并发现使用datepicker是最好的,但日期格式会导致JavaScript出现问题....
所以这是我的答案,可以开箱即用 .
这里可以看到小提琴DEMO
这是从另一个日期中减去一个日期的代码 . 此示例将日期转换为对象,因为getTime()函数将不起作用,除非它是Date对象 .