Moment .isAfter 没有正确返回

Moment .isAfter not returning correctly

我有一个以 UTC 时间存储的字符串。我想看看这个时间是否在当前 UTC 时间之后。我正在使用 momentjs 和 isAfter() 方法return当只有 1 小时的差异时,它的值不正确。

active_time 变量发生在 15:00 协调时间。 current_time 设置为 16:00 协调世界时。所以我认为 active_time.isAfter(current_time) 应该 return false 但它是 returning true。我怎样才能做到 return false?

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

代码:

//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?

查看toDate方法,看看内部js日期是什么:

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

这取决于您所在的时区

如果您的日期是 ISO8601 格式或时间戳,请不要使用 moment.isAfter。它比比较 2 个日期对象慢 150 倍: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 );

即使第一个日期字符串是 utc,您仍然需要在比较之前将时刻设置为 utc 模式。看看这里的文档: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>