0

I have an array of date object:

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'
]

I want to check if at least one of the dates inside the array is later than the current date (if there is any date which has not reached yet return true, if all of them past return false)

Spectric
  • 30,714
  • 6
  • 20
  • 43
Sara Ree
  • 3,417
  • 12
  • 48
  • Does this answer your question? [Check if date is in the past Javascript](https://stackoverflow.com/questions/8305259/check-if-date-is-in-the-past-javascript) – Pedro Henrique Jul 31 '21 at 20:08

3 Answers3

3

Use Array#some to parse each date and the > operator to check whether the date is later than the current date.

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);
Spectric
  • 30,714
  • 6
  • 20
  • 43
1

You can use Array.prototype.some for this:

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()));
Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31
1

Array.find should be sufficient for your problem I suppose

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)
)
KooiInc
  • 119,216
  • 31
  • 141
  • 177