javascript错误的日期/天计算

时间:2015-06-23 02:03:55

标签: javascript date days

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

如果我选择22,06,201522,07,2015等日期,则会显示31晚,这是错误的,因为6月只有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 个答案:

答案 0 :(得分:0)

您没有从日历月号中减去1:

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

月份为零索引。你可能还应该对结果进行舍入,就好像你越过夏令时一样,时间值不是偶数天,它会超过1小时(除非你越过两个边界......)

相关问题