在 JavaScript 中获取 2 个日期之间的差异? [英] Get difference between 2 dates in JavaScript?

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

问题描述

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

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.

推荐答案

这里有一种方法:

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

请注意,我们需要将日期括在引号中.其余代码获取以毫秒为单位的时间差,然后除以获取天数.日期需要 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 中获取 2 个日期之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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