Categories
JavaScript Answers

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

Spread the love

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *