Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/475.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript错误的日期/天数计算_Javascript_Date_Days - Fatal编程技术网

javascript错误的日期/天数计算

javascript错误的日期/天数计算,javascript,date,days,Javascript,Date,Days,我需要计算两次约会之间的夜数,这很有效,但很奇怪 如果我选择像22,062015和22,072015这样的日期,它会显示31个晚上,这是错误的,因为六月只有30天 如果我选择像01,072015和31,072015这样的日期,它会显示30晚,这是正确的 如果我选择像01,072015和1,082015这样的日期,它会显示31夜晚等 如果我选择像30,092015和30,102015这样的日期,它会显示31.0416668个奇怪且不正确的夜晚 希望你能帮我做这个。代码如下: var date11

我需要计算两次约会之间的夜数,这很有效,但很奇怪

如果我选择像
22,062015
22,072015
这样的日期,它会显示
31个晚上,这是错误的,因为六月只有
30天

如果我选择像
01,072015
31,072015
这样的日期,它会显示
30
晚,这是正确的

如果我选择像
01,072015
1,082015
这样的日期,它会显示
31
夜晚等

如果我选择像
30,092015
30,102015
这样的日期,它会显示
31.0416668
个奇怪且不正确的夜晚

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

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小时(除非您跨越两个边界…

这是我第一次看到日期以逗号分隔,而不是句点、斜杠或连字符分隔。也许您可以使用ISO yyyy mm dd标准重新格式化?希望这将对您有所帮助!!!!