diff --git a/sorting/stringMonthYear.js b/sorting/stringMonthYear.js new file mode 100644 index 0000000..8cfea59 --- /dev/null +++ b/sorting/stringMonthYear.js @@ -0,0 +1,46 @@ +/** + * This sorting plug-in will sort, in calendar order, data which + * is in the format "MMMM yyyy". Inspired by forum discussion: + * http://datatables.net/forums/discussion/1242/sorting-dates-with-only-month-and-year + * + * @name Date (MMMM yyyy) + * @anchor Sort dates in the format `MMMM yyyy` + * @author Phil Hurwitz + * + * @example + * $('#example').DataTable( { + * columnDefs: [ + * { type: 'stringMonthYear', targets: 0 } + * ] + * } ); + */ + +jQuery.extend(jQuery.fn.dataTableExt.oSort, { + "stringMonthYear-pre": function (s) { + var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; + + var dateComponents = s.split(" "); + dateComponents[0] = dateComponents[0].replace(",", ""); + dateComponents[1] = jQuery.trim(dateComponents[1]); + + var year = dateComponents[1]; + + var month = 0; + for (var i = 0; i < months.length; i++) { + if (months[i].toLowerCase() == dateComponents[0].toLowerCase()) { + month = i; + break; + } + } + + return new Date(year, month, 1); + }, + + "stringMonthYear-asc": function (a, b) { + return ((a < b) ? -1 : ((a > b) ? 1 : 0)); + }, + + "stringMonthYear-desc": function (a, b) { + return ((a < b) ? 1 : ((a > b) ? -1 : 0)); + } +}); \ No newline at end of file