javascript 错误的日期/天数计算
javascript wrong date / days calculation
我需要计算两个日期之间的晚数,它可以工作,但很奇怪。
如果我选择 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 小时(除非您跨越两个边界……)
我需要计算两个日期之间的晚数,它可以工作,但很奇怪。
如果我选择 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 小时(除非您跨越两个边界……)