Comparing two times with Moment JS

2019-01-06 17:19发布

I have a problem that requires me to take two times in 12 hour format and compare them, we have moment.js included in our project and we initially thought it would be as trivial as this:

var beginningTime = moment('8:45am');
var endTime = moment('9:00am');
console.log(beginningTime.isBefore(endTime)); //false???

Fiddle: http://jsfiddle.net/KyleMuir/M4R4z/

Is there something we are missing? It feels like this shouldn't be a hard problem to solve. When we perform any moment functions on our beginningTime or endTime it simply says NAN

4条回答
男人必须洒脱
2楼-- · 2019-01-06 17:27

As per documentation you are declaring moment variable incorrectly check allowed formates

http://momentjs.com/docs/#/parsing/string/

Instead of it you can use

var beginningTime = moment({
  h: 8,
  s: 45
});
var endTime = moment({
  h: 9,
  s: 0
});
console.log(beginningTime.isBefore(endTime)); //true
<script src="https://cdn.jsdelivr.net/momentjs/2.13.0/moment.min.js"></script>

查看更多
Deceive 欺骗
3楼-- · 2019-01-06 17:32

You should just open the console and try doing this manually: moment("8:45am").toDate()

It gives you Invalid Date, which is why you're not getting expected results. Whereas "2014-05-15 08:45" gives you a date.

查看更多
smile是对你的礼貌
4楼-- · 2019-01-06 17:37

If you are always dealing with the time in h:mma format, you can specify it when parsing...

var beginningTime = moment('8:45am', 'h:mma');
var endTime = moment('9:00am', 'h:mma');
console.log(beginningTime.isBefore(endTime)); // true
console.log(beginningTime.toDate()); // Mon May 12 2014 08:45:00
console.log(endTime.toDate()); // Mon May 12 2014 09:00:00
<script src="https://cdn.jsdelivr.net/momentjs/2.13.0/moment.min.js"></script>

It will use today as the date, so it won't work if you are spanning different days.

JSFiddle

查看更多
够拽才男人
5楼-- · 2019-01-06 17:49

8:45am and 9:00am are invalid dates

var beginningTime = moment('8:45am');
var endTime = moment('9:00am');
console.log(beginningTime.isValid(), endTime.isValid()) // FALSE

You should use a valid format: http://momentjs.com/docs/#/parsing/string/

And they suggest that for consistent results, should use http://momentjs.com/docs/#/parsing/string-format/

Eg.

moment("2010-10-20 4:30", "YYYY-MM-DD HH:mm"); // parsed as 4:30 local time
查看更多
登录 后发表回答