我需要计算两个日期之间的夜晚数,这很有效,但很奇怪。
如果我选择22,06,2015
和22,07,2015
这样的日期,它会显示31
晚,这是错误的,因为六月只有30
天。
如果我选择01,07,2015
和31,07,2015
这样的日期,它会显示30
晚,这是正确的。
如果我选择01,07,2015
和1,08,2015
这样的日期,它会显示我31
晚等。
如果我选择像30,09,2015
和30,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小时(除非您跨越了两个边界…)