首页 > 解决方案 > 在javascript中按天比较两个日期

问题描述

我试图在javascript中比较两个日期。比较日期很好,但我只想按天比较它们而忽略一天中的时间。如果不依赖像momentjs这样的库,这可能吗?

标签: javascript

解决方案


这是一个比较没有时间的日期的片段:

   var today = new Date();
    today.setHours(0, 0, 0, 0);
    d = new Date(my_value); 
    d.setHours(0, 0, 0, 0);

    if(d >= today){ 
        alert(d is greater than or equal to current date);
    }

这是一个函数,可以为您提供两天之间的确切差异:

function daysBetween(first, second) {

    // Copy date parts of the timestamps, discarding the time parts.
    var one = new Date(first.getFullYear(), first.getMonth(), first.getDate());
    var two = new Date(second.getFullYear(), second.getMonth(), second.getDate());

    // Do the math.
    var millisecondsPerDay = 1000 * 60 * 60 * 24;
    var millisBetween = two.getTime() - one.getTime();
    var days = millisBetween / millisecondsPerDay;

    // Round down.
    return Math.floor(days);
}

推荐阅读