Busted Mug

A blog that documents solutions to the most frustrating problems that occur during development in technologies such as Java, XML, AJAX, SQL, CSS and others that make me want to throw my coffee mug against the cube wall.

Wednesday, December 06, 2006

Javascript date sorting using regular expressions

First off, let me say that this guy is awesome. I've referenced many of his articles over the years and they're all very helpful. Specifically, I used his Date Sort article today. I was dealing with an array of dates in javascript and needed to order them. The functions he lists use a regular expression. These are rather funky to look at:
var dateRE = /^(\d{2})[\/\- ](\d{2})[\/\- ](\d{4})/;
but extremely useful and elegant. He also offers functions like:
function mdyOrdA(a, b){ a = a.replace(dateRE,"$3$1$2"); b = b.replace(dateRE,"$3$1$2"); if (a > b) return 1; if (a < b) return -1; return 0; }
that you can use with Array's sort method to elegantly sort like so:
dateArray = new Array('15/10/2000','28/05/1999', '17/09/2005','06/12/2004','02/01/1998'); dateArray.sort( mdyOrdA ); document.write('Ascending : ' + dateArray + '
Bravo, Mr. Chapman! Very elegant.


Post a Comment

<< Home