【问题标题】:Check if dates in array contains a date later than the current date检查数组中的日期是否包含晚于当前日期的日期
【发布时间】:2021-07-31 20:05:01
【问题描述】:

我有一个日期对象数组:

const dates = [
  '2021-11-01T19:49:08.678Z',
  '2021-11-01T20:13:27.954Z',
  '2021-08-31T19:15:16.452Z',
  '1983-04-16T20:18:39.802Z',
  '2022-02-02T20:26:14.992Z',
  '2022-02-02T20:30:36.374Z',
  '2022-02-02T20:33:09.266Z',
  '2022-02-02T20:35:34.615Z',
  '2022-02-02T20:44:19.131Z',
  '2022-02-02T20:48:17.274Z'
]

我想检查数组中的至少一个日期是否晚于当前日期(如果有任何尚未到达的日期返回true,如果所有日期都过去则返回false

【问题讨论】:

标签: javascript


【解决方案1】:

使用Array#some 解析每个日期,使用> 运算符检查日期是否晚于当前日期。

const arr = [
  '2021-11-01T19:49:08.678Z',
  '2021-11-01T20:13:27.954Z',
  '2021-08-31T19:15:16.452Z',
  '1983-04-16T20:18:39.802Z',
  '2022-02-02T20:26:14.992Z',
  '2022-02-02T20:30:36.374Z',
  '2022-02-02T20:33:09.266Z',
  '2022-02-02T20:35:34.615Z',
  '2022-02-02T20:44:19.131Z',
  '2022-02-02T20:48:17.274Z'
]

const hasPassed = arr.some(e => new Date(e) > new Date);
console.log(hasPassed);

【讨论】:

  • 这不起作用...它只比较日期而不是时间..
【解决方案2】:

您可以为此使用Array.prototype.some

const dates = [
    '2021-11-01T19:49:08.678Z',
    '2021-11-01T20:13:27.954Z',
    '2021-08-31T19:15:16.452Z',
    '1983-04-16T20:18:39.802Z',
    '2022-02-02T20:26:14.992Z',
    '2022-02-02T20:30:36.374Z',
    '2022-02-02T20:33:09.266Z',
    '2022-02-02T20:35:34.615Z',
    '2022-02-02T20:44:19.131Z',
    '2022-02-02T20:48:17.274Z',
];

// If they're strings
console.log(dates.some(d => new Date(d).valueOf() > Date.now()));

const asDates = dates.map(d => new Date(d));
// If they're actual Date objects
console.log(asDates.some(d => d.valueOf() > Date.now()));

const dates2 = [
    '1983-04-16T20:18:39.802Z',
];

console.log(dates2.some(d => new Date(d).valueOf() > Date.now()));

const asDates2 = dates2.map(d => new Date(d));
console.log(asDates2.some(d => d.valueOf() > Date.now()));

【讨论】:

    【解决方案3】:

    Array.find 我想应该足以解决您的问题

    const referenceDate = new Date();
    console.log([
      `2021-11-01T19:49:08.678Z`,
      `2021-11-01T20:13:27.954Z`,
      `2021-08-31T19:15:16.452Z`,
      `1983-04-16T20:18:39.802Z`,
      `2022-02-02T20:26:14.992Z`,
      `2022-02-02T20:30:36.374Z`,
      `2022-02-02T20:33:09.266Z`,
      `2022-02-02T20:35:34.615Z`,
      `2022-02-02T20:44:19.131Z`,
      `2022-02-02T20:48:17.274Z`
    ].find(d => new Date(d) > referenceDate)
    )

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 2023-03-19
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多