Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment .isAfter not returning correctly

I have a string that is stored in UTC time. I am trying to see if this time is after the current UTC time. I am using momentjs and the isAfter() method returns the incorrect value when there is only 1 hour difference.

The active_time variable happens at 15:00 utc. The current_time is set to 16:00 utc. So I think active_time.isAfter(current_time) should return false but it is returning true. How can I make it return false?

jsFiddle link: http://jsfiddle.net/Ln1bz1nx/

Code:

//String is already in utc time
var active_time = moment('2015-06-04T15:00Z', 'YYYY-MM-DD[T]HH:mm[Z]');

//Convert current time to moment object with utc time
var current_time = moment( moment('2015-06-04T16:00Z').utc().format('YYYY-MM-DD[T]HH:mm[Z]') ); 

console.log('active_time =',active_time);
console.log('current_time =',current_time);
console.log( active_time.isAfter(current_time) ); //Why does this return true?
like image 937
Mdd Avatar asked Jun 04 '15 19:06

Mdd


3 Answers

Even though the first date string is utc, you still need to put the moment into utc mode before you compare. Take a look at the docs here: http://momentjs.com/docs/#/parsing/utc/

//String is already in utc time, but still need to put it into utc mode
var active_time = moment.utc('2015-06-04T15:00Z', 'YYYY-MM-DD[T]HH:mm[Z]');

//Convert current time to moment object with utc time
var current_time = moment.utc('2015-06-04T16:00Z', 'YYYY-MM-DD[T]HH:mm[Z]');

console.log('active_time =',active_time.format());
console.log('current_time =',current_time.format());
console.log( active_time.isAfter(current_time) );
<script src="https://rawgit.com/moment/moment/develop/moment.js"></script>
like image 89
Alexander Lindsay Avatar answered Oct 06 '22 20:10

Alexander Lindsay


If your dates are ISO8601 formatted or timestamp, don't use moment.isAfter. It's 150 times slower than comparing 2 dates objects : http://jsperf.com/momentjs-isafter-performance

 var active_time = new Date('2015-06-04T15:00Z');
 var current_time = new Date('2015-06-04T16:00Z');

 console.log('active_time =',active_time);
 console.log('current_time =',current_time);
 console.log( active_time > current_time );
like image 8
Pierre Inglebert Avatar answered Oct 06 '22 21:10

Pierre Inglebert


Look at the toDate method to see what the internal js date is:

console.log('active_time =',active_time.toDate());
console.log('current_time =',current_time.toDate());
console.log( active_time.isAfter(current_time) ); //Why does this return true?

active_time = Thu Jun 04 2015 15:00:00 GMT-0700 (Pacific Daylight Time)
current_time = Thu Jun 04 2015 09:00:00 GMT-0700 (Pacific Daylight Time)
true

It's going to depend on what timezone you are in

like image 3
dave Avatar answered Oct 06 '22 20:10

dave