Earlier this week, I found a very interesting way of calculating the maximum dates from a set of dates with only one line of code. It came from this Stack Overflow answer. Here is a slightly modified version:
var dates = [ new Date("2011/06/25"), new Date("2011/06/28"), new Date("2011/06/27"), new Date("2011/06/26") ]; var maxDate = new Date(Math.max.apply(null, dates)); console.log(maxDate); // Tue Jun 28 2011 00:00:00 GMT-0400 (EDT)
Your results may be slightly different based on your timezone. This can be fixed with Date.UTC, but the purpose of the above is to show the most readable instead of adaptable solution.
This works firstly because dates are converted to the number of millesconds since 1 January 1970 (UNIX Epoch) when doing numerical or comparison operations. So:
console.log(new Date("2011/06/25") - new Date("2011/06/24")); // 86400000 one day console.log(1000 * 60 * 60 * 24); // 86400000 milleseconds in one day
Math.max takes a set of arguments to find the maximum of. So
apply has to be used to send an array as a set of arguments into
Math.max instead of doing a normal call.