Monday 1 September 2014

More Date sorting for Datatables

My use case was that I display a figure either for a month and year or a specific date (in UK date format (i.e. day/month/year)) and that I need to filter on that date within a DataTable. I of course used the cracking Moment.js but I need to parse dates in different ways depending upon whether or not the figure was MMMM YYYY or DD/MM/YYYY. Dead simple using a regex test:

$.extend( jQuery.fn.dataTableExt.oSort, {
    "date-time-odd-pre": function (a){
        if(/\d{1,2}\/\d{1,2}\/\d{4}/.test(a)){
            return parseInt(moment(a, "DD/MM/YYYY").format("X"), 10);
        }else{
            return parseInt(moment(a, "MMMM YYYY").format("X"), 10);
        }
    },
    "date-time-odd-asc": function (a, b) {
        return a - b;
    },
    "date-time-odd-desc": function (a, b) {
        return b - a;
    }
});

No comments:

Post a Comment