JavaScript Sort Dates

This section illustrates you how to sort an array of dates in JavaScript.

In the given example, we have created an instance of Array and defined some dates in order to sort them. For this purpose, first of all we have created a function ConvertDates() which converts the date into a more manageable format to sort the array of dates easily. Then we have created a function SortDates() that will call the function ConvertDates().

Following code sorts the array of dates:

for (z=0;z<dateArr.length-1;z++) {
for (y=0;y<(dateArr.length-(z+1));y++) {
if (eval(ConvertDate(dateArr[y+1])+ Sign[si] +ConvertDate(dateArr[y])) ) {
temp=dateArr[y+1]; 
dateArr[y+1] = dateArr[y]; 
dateArr[y]=temp;}}}

Here is the code:

<html>
<h2>JavaScript Sort Dates</h2>
<script>
var dateArr = new Array(
"Oct 20, 2008",
"Jun 5, 2001",
"Aug 12, 2005",
"Dec 30, 2009",
"Aug 24, 2006",
"May 17, 2002",
"Sep 15, 2003",
"Apr 21, 2007");
var Sign = new Array();
Sign["sort"] = "<";
months=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

function ConvertDate(dates){
M = dates.substring(0,dates.indexOf(" "));
D = dates.substring(dates.indexOf(" ")+1,dates.indexOf(","));
Y = dates.substring(dates.lastIndexOf(" ")+1,dates.length);
if (D.length == 1) {
D = "0"+D;
}
for (l=0;l<12;l++) {
if (months[l] == M) {
M = l+1; break;
}
}
if (M < 10) {
M = "0"+M;
}
return Y+""+M+""+D;
}
function SortDates(si){
for (z=0;z<dateArr.length-1;z++) {
for (y=0;y<(dateArr.length-(z+1));y++) {
if (eval(ConvertDate(dateArr[y+1])+ Sign[si] +ConvertDate(dateArr[y])) ) {
temp=dateArr[y+1]; 
dateArr[y+1] = dateArr[y]; 
dateArr[y]=temp;
}
}
}
document.write("<b>Sorted Dates</b><br>");
for (x=0;x<dateArr.length;x++) {
document.write(dateArr[x]+"<br>");
}
}
</script>
<input type=button value="Sort" onclick="SortDates('sort')">
</html>

Output will be displayed as:

On clicking the button, you will get the sorted dates:

Download Source Code: