0 Replies - 1114 Views - Last Post: 25 November 2013 - 07:21 AM

#1 andrewsw  Icon User is online

  • lashings of ginger beer
  • member icon

Reputation: 6342
  • View blog
  • Posts: 25,599
  • Joined: 12-December 12

Date formatting prototype

Posted 25 November 2013 - 07:21 AM

Description: Add the code to an included JS file and use like this: var date_formatted = date_instance.format("d mmm yy hh:nn:ss ap");. You can then insert this formatted version of the date into the DOM somewhere.There are a few examples available to format a Date. Mine allows you to specify 12/24 hrs, whether to include am/pm (or AM/PM) or to display suffixes 1st, 2nd, etc., for the days. Also, milliseconds.
Date.prototype.format = function (sFormat, twelve) {
    // Returns: A string version of the date.
    // Usage: date_instance.format("d mmm yy hh:nn:ss ap") or 
    // date_instance.format("dddd dd mmmm hh:nn", true)
    // Defaults to YYYY/MM/DD.
    // twelve == true for a 12hr clock, or just AP or ap within 
    // sFormat (for AM/PM or am/pm).
    // Use z or zzz for milliseconds and xx for suffixes (st, nd, etc.).
    var MonthNames = ["January", "February", "March", "April", "May", "June", 
        "July", "August", "September", "October", "November", "December"];
    var DayNames = [ "Sunday", "Monday", "Tueday", "Wednesday", "Thursday", 
        "Friday", "Saturday" ];
    var dDate = this || new Date(),
        D = dDate.getDate(), DDDD = DayNames[dDate.getDay()], 
        DDD = DDDD.substr(0,3),
        M = dDate.getMonth()+1, MMMM = MonthNames[dDate.getMonth()], 
        MMM = MMMM.substr(0,3),
        YYYY = dDate.getFullYear(), YY = ('' + YYYY).substr(2, 2),
        H = dDate.getHours(), N = dDate.getMinutes(), S = dDate.getSeconds(),
        Z = dDate.getMilliseconds(),
        ap = (H > 11) ? "pm" : "am",
        // pad with leading zeros, if required
        DD = ( D < 10 ? "0" : "" ) + D,
        MM = ( M < 10 ? "0" : "" ) + M,
        NN = ( N < 10 ? "0" : "" ) + N, 
        SS = ( S < 10 ? "0" : "" ) + S,
        ZZZ = ( Z < 10 ? "00" : (Z < 100 ? "0" : "") ) + Z, XX;
    var AP = (sFormat && (sFormat.toUpperCase().indexOf('AP')+1)) ? 
        ((sFormat.indexOf('ap')+1) ? ap : ap.toUpperCase()) : '';
    if (twelve || AP) {
        H = (H < 12) ? (H || 12) : ((H - 12) || 12);
    }
    var HH = ( H < 10 ? "0" : "" ) + H;
    XX = (D == 1 || D == 21 || D == 31) ? "st" : 
        ((D == 2 || D == 22) ? "nd" : ((D == 3 || D == 23) ? "rd" : "th"));
    sFormat = ( sFormat ) ? sFormat.toUpperCase() : 'YYYY/MM/DD';
    var sParsed = sFormat.replace(/D{1,4}|M{1,4}|Y{2,4}|H{1,2}|N{1,2}|S{1,2}|Z{1,3}|XX|AP/g,
        function (m) {
            try {
                return eval(m);
            } catch (e) {
                return '';
            }
        });
    return sParsed;
};


Is This A Good Question/Topic? 0
  • +

Page 1 of 1