javascript错误的日期/天数计算



我需要计算两个日期之间的夜晚数,这很有效,但很奇怪。

如果我选择22,06,201522,07,2015这样的日期,它会显示31晚,这是错误的,因为六月只有30天。

如果我选择01,07,201531,07,2015这样的日期,它会显示30晚,这是正确的。

如果我选择01,07,20151,08,2015这样的日期,它会显示我31晚等。

如果我选择像30,09,201530,10,2015这样的日期,它会显示我31.041666666666668的夜晚,这是奇怪和不正确的。

希望你能帮我做这个。这是代码:

var date11 = $("#in").val();
var date22 = $("#out").val();
// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date111 = date11.split('-');
date222 = date22.split('-');
// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date111[2], date111[1], date111[0]);
date2 = new Date(date222[2], date222[1], date222[0]);
// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);
// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;
// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;
// and finaly, in days :)
var timeDifferenceInDays = timeDifferenceInHours  / 24;

万分感谢!

您不会从日历月数中减去1:

date1 = new Date(date111[2], date111[1] - 1, date111[0]);
                                --------^^^^

月份为零索引。您可能还应该对结果进行四舍五入,就好像您跨越了夏令时边界,时间值不会是偶数天,它将超时1小时(除非您跨越了两个边界…)

最新更新