我需要使用JavaScript查找两个日期之间的天差,这是我的代码
我有开始日期和结束日期
var diff = Math.floor((Date.parse(enddate) - Date.parse(startdate)) / 86400000);
Run Code Online (Sandbox Code Playgroud)
它计算与当前时间的差。我需要找到给定日期之间的日期数。
例如,如果我输入的开始日期为2014年12月17日和2014年12月19日,则显示两天,但我需要计算天数17,18和19。它应显示为三天。
有人可以帮我吗?
您可以在进行比较之前将小时,分钟,秒和毫秒设置为0,以忽略一天中的时间,例如:
var startdate = "2014-12-17";
var enddate = "2014-12-19";
var start = new Date(startdate);
start.setHours(0, 0, 0, 0); // Sets hours, minutes, seconds, and milliseconds
var end = new Date(enddate);
end.setHours(0, 0, 0, 0);
var diff = Math.round((end - start) / 86400000) + 1; // See note below re `+ 1`
snippet.log("diff = " + diff); // 3Run Code Online (Sandbox Code Playgroud)
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>Run Code Online (Sandbox Code Playgroud)
关于这两个注意事项:
Math.round:这是因为如果时间跨度超过了夏令时边界,则该数字将减少一小部分,但会在舍入校正范围内。请注意,您必须舍入,截断地板,天花板,而不要截断。
+ 1:该行+ 1结尾处的,diff =是因为您的“差异”与众不同,因为您要计算开始和结束的天数。这很奇怪,可以说从一个星期一到下一个星期一的天数差是八而不是七,因为它将算在任一端的星期一。但是你说:
例如,如果我输入的开始日期为2014年12月17日和2014年12月19日,则显示的是两天,但我需要计算出天数17,18和19。
...所以你所需要的+ 1。两个日期之间没有正常的区别。
跨DST边界的示例(在许多时区中):
var start, end, diff;
start = new Date(2014, 2, 1); // March 1st 2014
end = new Date(2014, 5, 1); // May 1st 2014
diff = ((end - start) / (1000 * 3600 * 24)) + 1;
// diff won't *quite* be 93, because of the change to DST
// (assuming a timezone where DST changes sometime in
// March, as in most parts of the U.S., UK, and Canada
snippet.log("diff = " + diff + " instead of 93");
snippet.log("rounded = " + Math.round(diff));
// Similarly, at the other end:
start = new Date(2014, 9, 1); // October 1st 2014
end = new Date(2014, 11, 1); // December 1st 2014
diff = ((end - start) / (1000 * 3600 * 24)) + 1;
// diff won't *quite* be 62, because of the change to DST
// (assuming a timezone where DST changes sometime in
// March, as in most parts of the U.S., UK, and Canada
snippet.log("diff = " + diff + " instead of 62");
snippet.log("rounded = " + Math.round(diff));Run Code Online (Sandbox Code Playgroud)
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>Run Code Online (Sandbox Code Playgroud)
这种事情使我转向像这样的图书馆MomentJS。使用MomentJS,它将是:
var diff = moment(enddate).diff(moment(startdate), 'days') + 1;
Run Code Online (Sandbox Code Playgroud)
...这又+ 1是因为您对两个日期之间的时差的不寻常定义。