• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

JavaScript Date formatting prototype

JavaScript 水墨上仙 2541次浏览

JavaScript Date formatting prototype

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;
};


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明JavaScript Date formatting prototype
喜欢 (0)
加载中……