Australian Government date parsers for Tablesorter jQuery plug-in

Here are some custom parsers so particular Australian Government dates and times as defined by the Australian Government (Commonwealth) style manual sort properly with the great jQuery Tablersorter plug-in.

If you use dates or times in this format

  • 11 August 2012
  • Saturday 11 August 2012
  • 3 pm
  • 4:30 pm

and use the plug-in without a custom parser your dates will just sort based on the number, not knowing the context (eg, am vs pm).

Hopefully you will find these useful like I have. You are free to use and modify as you wish; I attach no license to the code. Please comment if you’ve got a better way, would like to contribute any similar parsers or have found them useful.

$.tablesorter.addParser({
	id: 'commonwealthdate',
	is: function (s) { return false; },
	format: function (s) {
		// Example: 1 August 2011
		var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
			t = s.split(' '),
			u = t[2] + '' + months.indexOf(t[1]) + '' + t[0];
		return Number(u);
	},
	type: 'numeric'
});
 
$.tablesorter.addParser({
	id: 'commonwealthdate-ldF',
	is: function (s) {  return false; },
	format: function (s) {
		// Example: Monday 14 March
		var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
			t = s.split(' '),
			u = months.indexOf(t[1]) + '' + t[1];
		return Number(u);
	},
	type: 'numeric'
});
 
$.tablesorter.addParser({
	id: 'commonwealthdate-ldFY',
	is: function (s) { return false; },
	format: function (s) {
		// Example: Monday 14 March 2011
		var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
			t = s.split(' '),
			u = t[3] + '' + months.indexOf(t[2]) + '' + t[1];
		return Number(u);
	},
	type: 'numeric'
});
 
$.tablesorter.addParser({
	id: 'commonwealth-time',
	is: function (s) { return false; },
	format: function (s) {
		// Example: 9:30 am || 10 pm || noon/midnight
		if (s.match(/noon/)) {
			s = '12:00';
		} else if (s.match(/midnight/)) {
			s = '00:00';
		}
		if (!s.match(/:/)) {
			// 10 pm to 10:00 pm
			var amORpm = (s.match(/am$/)) ? 'am' : 'pm';
			s = s.replace(' ' + amORpm, '') + ':00 ' + amORpm;
		}
		return $.tablesorter.formatFloat(new Date('2000/01/01 ' + s).getTime());
	},
	type: 'numeric'
});

If you are already sorting all tables on your site or just tables of a particular class you can get these working by adding class=”{sorter:’commonwealthdate’}” on your <th> in the HTML and use the metadata plug-in. The alternative is to call the JavaScript with a fixed column number using the headers option, but this is a bit less flexible.

Leave a Comment