简体   繁体   English

moment.js日期/时间比较

[英]moment.js date/time comparisons

I have the following code: 我有以下代码:

var timeCutoff = moment('05:00PM', 'h:mmA').format("MM/DD/YYYY hh:mmA")
var testTime = moment('11:00AM', 'h:mmA').format("MM/DD/YYYY hh:mmA");

if(testTime < timeCutoff){
    console.log(testTime + " before " + timeCutoff);
}
else{
    console.log(testTime + " after " + timeCutoff);
}

The idea here is if now's time is before 5PM, do something. 这里的想法是,如果现在是下午5点之前 ,请执行一些操作。 If the time is after 5PM, do something else. 如果时间是下午5点之后 ,请执行其他操作。

Here is the problem I am experiencing: 这是我遇到的问题:

testTime is set to ('11:00AM', 'h:mmA') and logs the "after" condition which is unexpected. testTime设置为('11:00AM','h:mmA')并记录“意外”条件。
testTime is set to ('12:00PM', 'h:mmA') and logs the "after" condition which is unexpected. testTime设置为('12:00PM','h:mmA')并记录“意外”条件。
testTime is set to ('01:00PM', 'h:mmA') and logs the "before" condition which is expected. testTime设置为('01:00PM','h:mmA')并记录预期的“之前”条件。
testTime is set to ('09:00PM', 'h:mmA') and logs the "after" condition which is expected. testTime设置为('09:00PM','h:mmA')并记录预期的“之后”条件。

I'm currently using moment.js 2.17.1 我目前正在使用moment.js 2.17.1

Any suggestions are greatly appreciated. 任何建议,不胜感激。 Thanks! 谢谢!

You should use the isBefore() method. 您应该使用isBefore()方法。

https://momentjs.com/docs/#/query/is-before/ https://momentjs.com/docs/#/query/is-before/

var timeCutoff = moment('05:00PM', 'h:mmA');
var testTime = moment('11:00AM', 'h:mmA');

if(testTime.isBefore(timeCutoff)) {
  console.log(testTime.format("MM/DD/YYYY hh:mmA") + " before " + timeCutoff.format("MM/DD/YYYY hh:mmA"));
}
else
{
  console.log(testTime.format("MM/DD/YYYY hh:mmA") + " after " + timeCutoff.format("MM/DD/YYYY hh:mmA"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM