【问题标题】:Moment .isAfter not returning correctly时刻 .isAfter 没有正确返回
【发布时间】:2015-06-05 11:32:37
【问题描述】:

我有一个以 UTC 时间存储的字符串。我正在尝试查看此时间是否在当前 UTC 时间之后。我正在使用 momentjs,当只有 1 小时的差异时,isAfter() 方法返回的值不正确。

active_time 变量发生在 15:00 UTC。 current_time 设置为 16:00 UTC。所以我认为active_time.isAfter(current_time) 应该返回false 但它正在返回true。我怎样才能让它返回false

jsFiddle 链接: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?

【问题讨论】:

  • 返回false给我:jsfiddle.net/Ln1bz1nx/3
  • 很奇怪。对我来说总是true。我使用的是 Macbook,我不知道这是否与它有关。
  • 我没有从 isAfter 获得可靠的结果。如果我在两个时刻都使用 .unix() ,我可以进行比较,否则如果它们位于不同的时区或来自不同的来源,它就不能可靠地工作。

标签: javascript momentjs


【解决方案1】:

即使第一个日期字符串是 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>

【讨论】:

    【解决方案2】:

    如果您的日期是 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 );
    

    【讨论】:

      【解决方案3】:

      查看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
      

      这取决于你所在的时区

      【讨论】:

      • 有没有办法检查这个?与我的时区相比,我得到的响应的格式为 YYYY-MM-DD[T]HH:mm[Z] 已经是 UTC。
      • 使用 moment.utc() 将日期创建为 UTC 日期。请参阅 momentjs.com/docs/#/parsing/utc/
      猜你喜欢
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      相关资源
      最近更新 更多