Moment .isAfter not returning correctly
I have a string that is stored in UTC. I am trying to see if this time comes after the current UTC time. I am using momentjs and the isAfter () method returns the wrong value when the difference is 1 hour less.
The active_time variable occurs at 15:00 utc. Current_time is set to 16:00 utc. So I think I active_time.isAfter(current_time)
should return false
, but returns true
. How can I get it back 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?
source to share
Even though the first date string is utc, you still need to put the moment in utc mode before comparing. 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>
source to share
If your dates are in ISO8601 format or timestamp then don't use moment.isAfter. This is 150 times slower than comparing two date 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 );
source to share
Have a look at the method toDate
to see what the js internal 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 depends on what time zone you are in
source to share