Try this:
String.prototype.getCorrectDate = function () {
var date = this.split(' ')[0];
var hours = this.split(' ')[1];
var dateSplitted = date.split('.');
return new Date(dateSplitted[2] + '.' + dateSplitted[1] + '.' + dateSplitted[0] + ' ' + hours);
};
var dates = ["16.08.1993 11:13", "16.08.1994 11:12", "13.08.1994 11:12", "13.08.1996 10:12", "08.08.1996 10:12"];
var sorted = dates.sort(function(a, b) {
return b.getCorrectDate() - a.getCorrectDate();
});
alert('First from sorted: '+ sorted[0]);
alert('Last from sorted: '+ sorted[sorted.length - 1]);
https://jsfiddle.net/Lcq6wqhb/
Javascript's native method sort
is used to sorting arrays, and we can pass callback function let's say sorting behavior
(Sorting an array of JavaScript objects).
But before sorting we need to transform date
strings to correct format, to be accepted new Date(dateString)
as parameter, otherwise it gives error Invalid Date
.
I'm transorming dd.mm.yyyy hh:MM
to yyyy.mm.dd HH:MM
using getCorrectDate
method