Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two times with Moment JS

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

like image 733
Kyle Muir Avatar asked May 12 '14 23:05

Kyle Muir


People also ask

How do you find the difference between two times using a moment?

To get the hour difference between two times with moment. js, we can use the duration , diff , asHours and asMinutes methods. For instance, we can write: const startTime = moment("12:26:59 am", "HH:mm:ss a"); const endTime = moment("06:12:07 pm", "HH:mm:ss a"); const duration = moment.

Is it good to use moment JS?

Moment. js is a fantastic time & date library with lots of great features and utilities. However, if you are working on a performance sensitive web application, it might cause a huge performance overhead because of its complex APIs and large bundle size.

What is Moment () in JavaScript?

Moment JS allows displaying of date as per localization and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm.


Video Answer


2 Answers

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

like image 172
Anthony Chu Avatar answered Oct 23 '22 09:10

Anthony Chu


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>
like image 7
Mudaser Ali Avatar answered Oct 23 '22 11:10

Mudaser Ali