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?
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>
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 );
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With