How to Get the Min and Max Dates in a JavaScript Date Array?

Sometimes, we want to get the min and max dates in a JavaScript date array.

In this article, we’ll look at how to the min and max dates in a JavaScript date array.

Get the Min and Max Dates in a JavaScript Date Array

We can use the Math.max and Math.min methods to get the max and min dates respectively.

For instance, we can write:

const dates = [];
dates.push(new Date("2011/06/25"));
dates.push(new Date("2011/06/26"));
dates.push(new Date("2011/06/27"));
dates.push(new Date("2011/06/28"));
const maxDate = new Date(Math.max(...dates));
const minDate = new Date(Math.min(...dates));
console.log(minDate);
console.log(maxDate);

To compute the maxDate and minDate, which are the max and min dates in the dates array respectively.

dates have multiple date objects.

We spread the dates array into Math.max and Math.min, which will convert the dates entries into UNIX timestamps, which are numbers.

The spread operator also spread the numbers as arguments of both methods.

Then we pass in the returned timestamp into the Date constructor to recreate them as dates.

Therefore minDate is:

'Sat Jun 25 2011 00:00:00 GMT-0700 (Pacific Daylight Time)'

And maxDate is:

'Tue Jun 28 2011 00:00:00 GMT-0700 (Pacific Daylight Time)'

Conclusion

We can use the Math.max and Math.min methods to get the max and min dates respectively.

Then we spread the dates array into Math.max and Math.min, which will convert the dates entries into UNIX timestamps, which are numbers.

The spread operator also spread the numbers as arguments of both methods.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics