繁体   English   中英

javascript错误的日期/天数计算

[英]javascript wrong date / days calculation

我需要计算两个日期之间的夜晚数,它可以工作,但是很奇怪。

如果我选择22,06,2015年6月22日和22,07,2015 31 22,07,2015日这样的日期,它将显示31夜,这是错误的,因为6月只有30天。

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

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

如果我选择30,09,201530,10,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小时(除非您越过两个边界……)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM