【问题标题】:MomentJS, dynamic current yearMomentJS,动态当前年份
【发布时间】:2021-09-28 07:29:32
【问题描述】:

我有这个代码:

const date = moment(person.indefiniteContractDate
  .toISOString()
  .substring(2),
  'YY-MM-DD');

if (date.isAfter('2020-08-15'))

我想询问当年,但总是'08-15',我该怎么做?

【问题讨论】:

  • 嗯,新的 Date.getFullYear()
  • YY-MM-DD 是一种不同于您使用 .isAfter 查询搜索的字符串格式。那就是寻找格式 YYYY-MM-DD
  • moment 不接受Date 吗?只需致电moment(person.indefiniteContractDate)。如果您需要将小时/分钟/秒设置为零,请在传入Date 对象后执行此操作。此外,时刻是 EOL(生命周期结束),您应该改用 Luxon

标签: javascript momentjs


【解决方案1】:

你可以去moment('08-15','MM-DD')

这将为您提供当年的 08-15

所以我认为你的代码可能是

const date = moment(person.indefiniteContractDate
  .toISOString()
  .substring(2),
  'YY-MM-DD');

const compareDate = moment('08-15','MM-DD');

if (date.isAfter(compareDate))

【讨论】:

    【解决方案2】:

    moment 函数能够接受Date。只需致电moment(person.indefiniteContractDate)。如果您需要将小时/分钟/秒设置为零,请在传入Date 对象后执行此操作。有一个名为startOf 的函数可以处理将当天的时间设置为零。

    注意:时刻为 EOL(生命周期结束),您应该改用 Luxon

    // IF
    {
      const person = { indefiniteContractDate: new Date() }
      // https://stackoverflow.com/a/19699447/1762224
      const date = moment(person.indefiniteContractDate).startOf('day');
    
      if (date.isAfter('2020-08-15')) {
        console.log('AFTER!');
      }
    }
    
    // ELSE
    {
      const person = { indefiniteContractDate: new Date(2020, 7, 13) }
      const date = moment(person.indefiniteContractDate).startOf('day');
    
      if (date.isAfter('2020-08-15')) {
        console.log('AFTER!');
      } else {
        console.log('BEFORE!'); // <-- Here
      }
    }
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 2022-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多