Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find minimum and maximum dates

There is an array:

var a = new Array();

It contains date entries like this: '2012-09-12 09:20', etc

I need to find minimum and maximum dates using javascript. This code does not work with time values.

var minT = Math.min.apply(Math, a);
var maxT = Math.max.apply(Math, a);

How can I solve this problem in javascript? It seems to be quite complex as I'm not very experienced in this language.

like image 713
You Kuper Avatar asked Feb 12 '26 23:02

You Kuper


1 Answers

If your array contains Date objects, then this should work. If it just contains strings like '2012-09-12 09:20', then you can sort them, and get the 1st and last elements.

a.sort(function(a, b){
    return Date.parse(a) - Date.parse(b);
});

var maxT = a[a.length-1];
var minT = a[0];
like image 80
Rocket Hazmat Avatar answered Feb 15 '26 13:02

Rocket Hazmat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!