【问题标题】:Compare two dates using valueOf()使用 valueOf() 比较两个日期
【发布时间】:2019-04-24 05:55:52
【问题描述】:
 const startDayOfTheWeek: number = moment().startOf('isoweek' as moment.unitOfTime.StartOf).valueOf();
 if (this.card.dateScheduled.valueOf() < startDayOfTheWeek) {
     this.card.dateScheduled = this.card.dateDue;
 }

当使用valueOf()this.card.dateScheduled.valueOf() 时,这给了我一个实际日期的值。不是相对于 1970 年的毫秒数(也就是 Unix 时间戳/纪元)。

这是为什么呢?

【问题讨论】:

  • “给我一个实际日期的值”是什么意思,您如何验证该值是什么?
  • 它给了我 datecheduled 的实际值。 ex"2019-04-10T16:00:00Z" 但是当 datescheduled 的值是 "1970-01-01T00:00:00Z" 它给我 0 使用的值。

标签: javascript angularjs typescript date


【解决方案1】:

在 moment.js 中有许多有用的方法可以比较日期,例如 isAfterisBefore。所以在你的情况下使用:

if (moment(this.card.dateScheduled).isBefore(startDayOfTheWeek))

【讨论】:

    【解决方案2】:

    我认为您可以从内置功能中获益。

    这是一个比较javascript 中日期的示例。

    const first = +new Date(); // current date
    const last = +new Date(2014, 10, 10); // old date 
    
    console.log(first);
    console.log(last);
    // comparing the dates
    console.log(first > last);
    console.log(first < last);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      • 2011-09-01
      • 2013-11-29
      相关资源
      最近更新 更多