如何使用javascript查找两个日期之间的天数差异

时间:2014-12-17 11:44:35

标签: javascript date

我需要使用javascript找到两个日期之间的天差,这是我的代码

我有开始日期和结束日期

var diff = Math.floor((Date.parse(enddate) - Date.parse(startdate)) / 86400000);

计算与当前时间的差异。我需要找到给定日期之间的日期数。

例如,如果我将输入开始日期设为2014年12月17日和2014年12月19日,则显示两天,但我需要计算天数17,18和19.它应显示天数为三天

有人帮我吗?

1 个答案:

答案 0 :(得分:5)

您可以在进行比较之前将小时,分钟,秒和毫秒设置为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); // 3

<!-- 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>
&#13;
&#13;
&#13;

关于此的两点说明:

  1. Math.round:这是因为如果时间跨度超过夏令时间界限,则该数字会偏离一小部分,但在舍入校正它的范围内。请注意,您必须舍入,而不是截断,地板,天花板。

  2. + 1+ 1行末尾的diff =是因为您的差异&#34;是不寻常的,因为你计算包括起点和终点。这很奇怪,它会说从一个星期一到下一个星期的天数差异是,而不是七天,因为它会计算两端的星期一。但你说:

      

    例如,如果我将输入开始日期设为2014年12月17日和2014年12月19日,则显示两天,但我需要计算17,18和19天的天数。

    ...所以你需要+ 1。两个日期之间的正常差异不会有。

  3. 跨越DST边界的示例(在许多时区中):

    &#13;
    &#13;
    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));
    &#13;
    <!-- 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>
    &#13;
    &#13;
    &#13;

    这使我转向像MomentJS这样的图书馆。使用MomentJS,它将是:

    var diff = moment(enddate).diff(moment(startdate), 'days') + 1;
    

    ... + 1又是由于您对两个日期之间差异的不寻常定义。