How do I find the earliest of a set of dates. Currently I have the following code which works just fine:
var dates = [date1,date2]; // list of javascript dates
var start = moment(new Date(9999, 0, 1))
// I wished this was one line in momentjs + underscorejs
_.forEach(dates, (date) => {
if (moment(date).isBefore(start)) {
start = moment(date);
}
});
I was hoping there was a neater way (in one line). I would prefer to use a simpler function in Underscore (min does not work on dates) / momentjs.
I found _.min is reliable on moment
instances. The following works:
var dates = _.map([date1,date2],function(date){return moment(date)});
var start = _.min(dates);
nevermind.
var earliest = new Date(Math.min.apply(null, dates))
see mdn Function.apply
Math.min(arg1,arg2,...argN)
finds the lowest of N numeric arguments.
Because of how Function.prototype.apply
works, Math.min.apply
takes two arguments, a
this
setting, which appears to be unneeded here, and a arg
array
.
The numeric representation of a date is the ms since 1970. A date coerced to a number will yield this value. A new date object is initialized to this lowest value, which is the same date as the earliest date but not the same object.
This is similar to @fardjad's approach, but does not need the underscore.js library for _.min., and is shortened by the use of func.apply, which should be common javascript to most recent browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With