Saturday, February 2, 2008

Easy Date Formatter

This should do the trick for most uses:
/** 
 * takes a string in form 'd/m/Y'
 * 
 * d => day (2 digits, leading 0)
 * D => day (2 digits, no leading)
 * l => day (of week, text, 3 chars)
 * L => day (of week, text, full length)
 * 
 * m => month (2 digits, leading 0)
 * M => month (2 digits, no leading 0)
 * f => month (text, 3 chars)
 * F => month (text, full length)
 * 
 * y => year (2 digits)
 * Y => year (4 digits)
 * 
 * g => hour (12hr, leading 0)
 * G => hour (12hr, no leading)
 * i => minute
 * s => second
 * t => hour (12hr, formatted with am/pm)
 * 
 * @param {String} format String for the formatting of this Date object
 * @return {String}
 */
Date.prototype.format = (function () {
    var days = ['Sun', 'Mon', 'Tue',
        'Wed', 'Thu', 'Fri', 'Sat'];
    var fulldays = ['Sunday', 'Monday', 'Tuesday',
        'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    var months = ['Jan', 'Feb', 'Mar',
        'Apr', 'May', 'Jun',
        'Jul', 'Aug', 'Sep',
        'Oct', 'Nov', 'Dec'];
    var fullmonths = ['January', 'February', 'March',
        'April', 'May', 'June',
        'July', 'August', 'September',
        'October', 'November', 'December'];

    function twoDigits(n) {
        return (n<10? '0':'')+n;
    }

    return function formatDate(format) {
        var d = this;

        var matches = this.matches || {
            'd': function () { return twoDigits(d.getDate()); },
                'D': function () { return d.getDate()+''; },
                'l': function () { return days[d.getDay()]; },
                'L': function () { return fulldays[d.getDay()]; },
                'm': function () { return twoDigits(d.getMonth()+1); },
                'M': function () { return d.getMonth()+1; },
                'f': function () { return months[d.getMonth()]; },
                'F': function () { return fullmonths[d.getMonth()]; },
                'y': function () { return (d.getFullYear()+'').slice(2, 4); },
                'Y': function () { return (d.getFullYear()+''); },
                'g': function () { return twoDigits(d.getHours()%12); },
                'G': function () { return d.getHours()%12+''; },
                'i': function () { return twoDigits(d.getMinutes()); },
                's': function () { return twoDigits(d.getSeconds()); },
                't': function () { return (d.getHours() > 11? 'am' : 'pm'); }
        };
        this.matches = matches;

        return format.replace(/[dDlLmMfFyYgGist]/g, function (match) {
            return matches[match]();
        });
    };
})();

No comments: