Home > Mobile >  Loop through array of Date Objects and compare which one is latest and earliest
Loop through array of Date Objects and compare which one is latest and earliest

Time:07-21

If I have this structure:

 const datesList = [2022-07-15T19:41:12.620Z, 2022-07-20T11:21:52.596Z, 2022-07-13T11:21:50.596Z]

How can I loop through it and find out which one is the later and the earlier date?

I've tried using forEach loop and its not working..

CodePudding user response:

You can compare using getTime() which gets the time in ms since 1970

var dateList = [new Date(Date.parse("2022-07-15T19:41:12.620Z")), new Date(), new Date( 5), new Date(1236876666273)]

console.log(dateList.sort(function(a, b) {
  if (a.getTime() < b.getTime()) {
    return -1
  }
  if (a.getTime() > b.getTime()) {
    return 1
  }
  return 0
}))

CodePudding user response:

  • Date.parse() returns the number of milliseconds since January 1, 1970, 00:00:00 UTC of string input for valie date.
  • I just used dort function of es6.

const datesList = ["2022-07-15T19:41:12.620Z", "2022-07-20T11:21:52.596Z", "2022-07-13T11:21:50.596Z"];
console.log(datesList.sort((a, b) => Date.parse(a) - Date.parse(b)));

CodePudding user response:

  1. Get each string date, abd parse them into timestamp numbers
    .map(d => Date.parse(d))
    
  2. Sort the array of timestamp numbers
    .sort((a, b) => a - b)
    
  3. Convert the numbers into date strings
    .map(t => new Date(t));
    

const dates = ['2022-07-15T19:41:12.620Z', '2022-07-20T11:21:52.596Z', '2022-07-13T11:21:50.596Z'];
 
 let output = dates
 .map(d => Date.parse(d))
 .sort((a, b) => a - b)
 .map(t => new Date(t));
 
console.log(output);

  • Related