To improve the sorting of dates, you can use an anonymous function with the sort()
method:
var dates = ['10-Jan-2013','12-Dec-2013','1-Sep-2013','15-Sep-2013'],
orderedDates = dates.sort(function(a,b){
return Date.parse(a) > Date.parse(b);
});
console.log(orderedDates); // ["10-Jan-2013", "1-Sep-2013", "15-Sep-2013", "12-Dec-2013"]
var dates = ['10-Jan-2013', '12-Dec-2013', '1-Sep-2013', '15-Sep-2013'],
orderedDates = dates.sort(function(a, b) {
return Date.parse(a) > Date.parse(b);
});
console.log(orderedDates);
Check out the JS Fiddle demo here.
Take note of using an array like
['10-Jan-2013','12-Dec-2013','1-Sep-2013','15-Sep-2013']
containing quoted date strings.
The code above will provide an array of dates in ascending order; for just the earliest date, access orderedDates[0]
.
A modified approach to display only the earliest date – as per the original request – is shown below:
var dates = ['10-Jan-2013', '12-Dec-2013', '1-Sep-2013', '15-Sep-2013'],
earliest = dates.reduce(function (pre, cur) {
return Date.parse(pre) > Date.parse(cur) ? cur : pre;
});
console.log(earliest); // 10-Jan-2013
var dates = ['10-Jan-2013', '12-Dec-2013', '1-Sep-2013', '15-Sep-2013'],
earliest = dates.reduce(function(pre, cur) {
return Date.parse(pre) > Date.parse(cur) ? cur : pre;
});
console.log(earliest);
Here's another JS Fiddle demo for reference.
For more information, check out these resources: