JavaScript 如何计算两个日期之间的天数
在JavaScript中计算两个日期之间的天数需要使用日期对象进行计算。首先,使用内置的JavaScript getTime()函数 来获取日期的内部毫秒值。一旦两个日期都被转换,可以通过将较晚的日期减去较早的日期来返回毫秒级差异。然后,通过将两个日期的毫秒级差异除以一天的毫秒数来计算最终结果。
语法:
Date.getTime()
方法1
- 使用 new Date() 定义两个日期。
- 使用 date2.getTime() – date1.getTime(); 计算两个日期的时间差。
- 计算两个日期之间的天数,将两个日期的时间差除以一天的毫秒数 (10006060*24)
- 使用 document.write() 打印最终结果。
示例1: 以下JavaScript程序将说明解决方案
<script type="text/javascript">
// JavaScript program to illustrate
// calculation of no. of days between two date
// To set two dates to two variables
var date1 = new Date("06/30/2019");
var date2 = new Date("07/30/2019");
// To calculate the time difference of two dates
var Difference_In_Time = date2.getTime() - date1.getTime();
// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
//To display the final no. of days (result)
console.log("Total number of days between dates <br>"
+ date1 + "<br> and <br>"
+ date2 + " is: <br> "
+ Difference_In_Days);
</script>
输出:
Total number of days between dates
Sun Jun 30 2019 00:00:00 GMT-0700 (Pacific Daylight Time)
and
Tue Jul 30 2019 00:00:00 GMT-0700 (Pacific Daylight Time) is:
30
方法2
- 使用 new date() 获取当前日期以及圣诞节日期,通过 date.getFullYear() 来获取年份(JavaScript中0-11代表月份)。
- 通过if条件判断来计算如果圣诞节已经过去了,计算当前日期与明年圣诞节之间的天数。
- 使用 Math.round(christmas() – present_date.getTime()) 将圣诞节日期与当前日期的毫秒数相减,再除以一天的毫秒数来计算结果,并转换为天数。
示例2: 在这个示例中,我们计算了距离圣诞节的天数。
<script type="text/javascript">
// One day Time in ms (milliseconds)
var one_day = 1000 * 60 * 60 * 24
// To set present_dates to two variables
var present_date = new Date();
// 0-11 is Month in JavaScript
var christmas_day = new Date(present_date.getFullYear(), 11, 25)
// To Calculate next year's Christmas if passed already.
if (present_date.getMonth() == 11 && present_date.getdate() > 25)
christmas_day.setFullYear(christmas_day.getFullYear() + 1)
// To Calculate the result in milliseconds and then converting into days
var Result = Math.round(christmas_day.getTime()
- present_date.getTime()) / (one_day);
// To remove the decimals from the (Result) resulting days value
var Final_Result = Result.toFixed(0);
//To display the final_result value
console.log("Number of days remaining till christmas <br>"
+ present_date + "<br> and <br>"
+ christmas_day + " is: <br> "
+ Final_Result);
</script>
输出:
Number of days remaining till christmas
Sun Jun 30 2019 11:33:51 GMT-0700 (Pacific Daylight Time)
and
Wed Dec 25 2019 00:00:00 GMT-0800 (Pacific Standard Time) is:
178