我如何获得JavaScript中两个日期之间的天数?

我如何获得JavaScript中两个日期之间的天数? 例如,给定输入框中的两个日期:

<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>

<script>
  alert(datediff("day", first, second)); // what goes here?
</script>

这里是一个快速和肮脏的实施datediff ,作为概念验证作为问题提出来解决这个问题。 它依赖于这样的事实,即可以通过减去两个日期之间的时间间隔来获取经过的毫秒数,这会将它们强制为它们的原始数值(自1970年初以来的毫秒数)。

// new Date("dateString") is browser-dependent and discouraged, so we'll write
// a simple parse function for U.S. date format (which does no error checking)
function parseDate(str) {
    var mdy = str.split('/');
    return new Date(mdy[2], mdy[0]-1, mdy[1]);
}

function datediff(first, second) {
    // Take the difference between the dates and divide by milliseconds per day.
    // Round to nearest whole number to deal with DST.
    return Math.round((second-first)/(1000*60*60*24));
}

alert(datediff(parseDate(first.value), parseDate(second.value)));
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>


获取两个日期之间差异的最简单方法是:

var diff =  Math.floor(( Date.parse(str2) - Date.parse(str1) ) / 86400000); 

你得到不同的日子(或NaN,如果一个或两个不能被解析)。 解析日期以毫秒为单位给出结果,并在白天得出结果,您必须将结果除以24 * 60 * 60 * 1000

如果你想要它除以天,小时,分钟,秒和毫秒:

function dateDiff( str1, str2 ) {
    var diff = Date.parse( str2 ) - Date.parse( str1 ); 
    return isNaN( diff ) ? NaN : {
        diff : diff,
        ms : Math.floor( diff            % 1000 ),
        s  : Math.floor( diff /     1000 %   60 ),
        m  : Math.floor( diff /    60000 %   60 ),
        h  : Math.floor( diff /  3600000 %   24 ),
        d  : Math.floor( diff / 86400000        )
    };
}

这是我重构版本的James版本:

function mydiff(date1,date2,interval) {
    var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
    date1 = new Date(date1);
    date2 = new Date(date2);
    var timediff = date2 - date1;
    if (isNaN(timediff)) return NaN;
    switch (interval) {
        case "years": return date2.getFullYear() - date1.getFullYear();
        case "months": return (
            ( date2.getFullYear() * 12 + date2.getMonth() )
            -
            ( date1.getFullYear() * 12 + date1.getMonth() )
        );
        case "weeks"  : return Math.floor(timediff / week);
        case "days"   : return Math.floor(timediff / day); 
        case "hours"  : return Math.floor(timediff / hour); 
        case "minutes": return Math.floor(timediff / minute);
        case "seconds": return Math.floor(timediff / second);
        default: return undefined;
    }
}
链接地址: http://www.djcxy.com/p/36707.html

上一篇: How do I get the number of days between two dates in JavaScript?

下一篇: How do I calculate number of days between two dates using Python?