JavaScript - 比较日期

时间:2014-12-20 09:22:45

标签: javascript html

我有个问题。我想比较今天和其他自制日期的日期。今天的日期称为a,自制日期的名称为b。如果a稍后b我想做某事,但是如何做。日期格式应为year,month,day,hour,minute,second,例如:2015,03,20,09,58,44

1 个答案:

答案 0 :(得分:0)

// First date is older

var a = new Date(2015,03,20,09,58,44).valueOf(),
b = new Date(2015,04,20,09,58,44).valueOf();

console.log((a > b), (a < b), (a === b)); // false, true, false

// Second date is older

var c = new Date(2015,03,20,09,58,44).valueOf(),
d = new Date(2015,02,20,09,58,44).valueOf();

console.log((c > d), (c < d), (c === d)); // true, false, false

// Same date

var now = new Date().valueOf(),
now2 = new Date().valueOf();

console.log((now > now2), (now < now2), (now === now2)); // false, false, true

// As a function

function isLater(a, b) {
    a = a.valueOf();
    b = b.valueOf();

    if (a > b) {
        return true;
    } else if (a < b) {
        return false;
    } else if (a === b) {
        // edge case
    }
}