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
As per documentation you are declaring moment variable incorrectly check allowed formates
http://momentjs.com/docs/#/parsing/string/
Instead of it you can use
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.
If you are always dealing with the time in
h:mma
format, you can specify it when parsing...It will use today as the date, so it won't work if you are spanning different days.
JSFiddle
8:45am
and9:00am
are invalid datesYou 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.