Javascript比较两个日期时间

时间:2017-12-07 10:22:04

标签: javascript jquery momentjs

我需要比较两个日期时间。日期时间的格式为:DD-MM-YYYY hh:mm:ss。

这是我的代码:

expirationDate = someDate;
var now = moment().format("DD-MM-YYYY hh:mm:ss");

if(moment(expirationDate).isBefore(now)){
    console.log("Past");        
} else {
    console.log("Future");
}

对于这个日期时间它很有用:

Now: 07-12-2017 11:15:09
Expiration date: 07-12-2017 10:14:10
it return Past

但为此它不起作用:

Now: 07-12-2017 11:15:03
Expiration date: 15-12-2016 05:59:00
it return Future

我也试过if(Date.parse(expireDate)< Date.parse(now))它也无法正常工作。 有谁知道问题出在哪里,还是有其他方法来比较两个日期时间?

1 个答案:

答案 0 :(得分:4)

您需要指定日期字符串的格式。

if (moment().isAfter(moment(expirationDate, 'DD-MM-YYYY HH:mm:ss'))) {
  console.log("Past");
} else {
  console.log("Future");
}