在javascript中的两个日期之间有所区别? [英] Get difference between 2 dates in javascript?

查看:96
本文介绍了在javascript中的两个日期之间有所区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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.

推荐答案

这是一种方式

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

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

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.

这篇关于在javascript中的两个日期之间有所区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆