【问题标题】:Moment giving wrong result when comparing dates比较日期时给出错误结果的时刻
【发布时间】:2020-03-20 04:01:18
【问题描述】:

我正在尝试比较 2 个日期,但出现错误。

这些是我的功能:

const validateDate = (date: string): Moment => {
  return moment(`${moment().year()}/${date}`);
};

export const themes: Theme[] = [{
  siteCode: '',
  costCenter: '',
  theme: 'spring',
  bannerImage: 'spring.jpg',
  cssOverride: 'springThemeStyles.scss',
  endDate: moment(validateDate('6/19')).toDate(),
  startDate: moment(validateDate('3/20')).toDate()
}];

export const getActiveTheme = (): any => {
  const now = moment().toDate();

  console.log(now); // Thu Mar 19 2020 21:56:10 GMT-0600 (Central Standard Time)
  console.log(themes[0].startDate); // Fri Mar 20 2020 00:00:00 GMT-0600 (Central Standard Time)
  console.log(themes[0].startDate >= now); // true

  return themes.map((t: Theme) => {
    if (t.startDate >= now) { // this is always true I don't know why
      if (t.theme.toLowerCase() === 'spring') {
        return require('../../../styles/spring.theme.scss');
      }

      return null;
    }
  });
};

我不明白为什么if (t.startDate >= now) {...} 的条件总是true。

有什么想法吗?

【问题讨论】:

  • 2020 年 3 月 20 日星期五 00:00:00 GMT-0600 大于 2020 年 3 月 19 日星期四 21:56:10 GMT-0600,因此条件始终为真。

标签: javascript typescript ecmascript-6 momentjs


【解决方案1】:

这仅仅是因为 startDate 是 2020 年 3 月 20 日星期五 而 now 是 2020 年 3 月 19 日星期四 strong> 所以很明显 startDate >= now 应该是真的

由于您已将 startDate 设置为 20 日,当 now 为 21 日时,startDate >= now 将为 false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    相关资源
    最近更新 更多