本文介绍了如何获得两个日期之间的天数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算两个日期之间的天数.我已经检查了这个链接的代码如何计算之间的天数两个日期使用 JavaScript?.

I need to calculate the number of days between 2 date. I have check the codes given this link How to calculate the number of days between two dates using JavaScript?.

在此示例中,如果输入 2012,02,29 和 2012,03,01,则输出为 3.实际答案应为 1.这些还有其他方法可以计算 2 个日期之间的天数吗?

In this example if give input 2012,02,29 and 2012,03,01 it gives output as 3. Actual answer should be 1. These there any other methods to calculate the number of days between 2 dates ?

推荐答案

对我有用 - 记住 JS 中的月份从 0 开始,所以这里是 2012 年 2 月 29 日至 3 月 1 日

Works for me - remember months in JS start at 0 so here are February 29th to March 1st 2012

var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2012, 1, 29, 12, 0, 0, 0); // 29th of Feb at noon your timezone
var secondDate = new Date(2012, 2, 1, 12, 0, 0, 0); // 1st of March at noon

var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
console.log(firstDate, "to", secondDate, "\nDifference: " + diffDays + " day");

这篇关于如何获得两个日期之间的天数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 04:36