最新通知
js格式化时间函数format
阅读次数:737 最后编辑时间:2021年12月04日

概述

通过prototype对象属性,使您有能力向对象添加属性和方法,来向Date对象中添加方法。

方法一

// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") >> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      >> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {        
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
调用:
var time1 = new Date().Format("yyyy-MM-dd");
var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss");

方法二

Date.prototype.pattern = function(fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+" : this.getDate(), //日
        "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时
        "H+" : this.getHours(), //小时
        "m+" : this.getMinutes(), //分
        "s+" : this.getSeconds(), //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S" : this.getMilliseconds() //毫秒
    };
    var week = {
        "0" : "/u65e5",
        "1" : "/u4e00",
        "2" : "/u4e8c",
        "3" : "/u4e09",
        "4" : "/u56db",
        "5" : "/u4e94",
        "6" : "/u516d"
    };
    if(/(y+)/.test(fmt)){
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    if(/(E+)/.test(fmt)){
        fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);
    }
    for(var k in o){
        if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
    return fmt;
}
调用:
var date = new Date();
window.alert(date.pattern("yyyy-MM-dd hh:mm:ss"));

方法三

Date.prototype.Format = function(mask) {
    var d = this;
    var zeroize = function(value, length) {
        if (!length) length = 2;
        value = String(value);
        for (var i = 0, zeros = ''; i < (length - value.length); i++) {
        zeros += '0';
        }
        return zeros + value;
    };
    return mask.replace(/d{1,4}|M{1,4}|S{1,3}|yy(?:yy)?|([hHmsaAZqQwW])\1?|[llLoszz]|"[^"]*"|'[^']*'/g,
        function($0) {
            switch ($0) {
                case 'd': // 日期一位
                    return d.getDate();
                case 'dd': // 日期两位
                    return zeroize(d.getDate());
                case 'ddd': // 星期 简写
                    return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
                case 'dddd': // 星期 英文
                    return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
                    'Saturday'
                    ][d.getDay()];
                case 'M': // 月份一位
                    return d.getMonth() + 1;
                case 'MM': // 月份两位
                    return zeroize(d.getMonth() + 1);
                case 'MMM': // 月份英文简写
                    return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
                    'Nov', 'Dec'
                    ][d.getMonth()];
                case 'MMMM': // 月份英文
                    return ['January', 'February', 'March', 'April', 'May', 'June', 'July',
                    'August', 'September', 'October', 'November', 'December'
                    ][d.getMonth()];
                case 'yy': // 年两位
                    return String(d.getFullYear()).substr(2);
                case 'yyyy': // 年四位
                    return d.getFullYear();
                case 'h': // 12小时一位
                    return d.getHours() % 12 || 12;
                case 'hh': // 12小时两位
                    return zeroize(d.getHours() % 12 || 12);
                case 'H': // 24小时制一位
                    return d.getHours();
                case 'HH': // 24小时制两位
                    return zeroize(d.getHours());
                case 'm': // 分钟一位
                    return d.getMinutes();
                case 'mm': // 分钟两位
                    return zeroize(d.getMinutes());
                case 's': // 秒一位
                    return d.getSeconds();
                case 'ss': // 秒两位
                    return zeroize(d.getSeconds());
                case 'SSS': // 毫秒三位
                    return zeroize(d.getMilliseconds(), 3);
                case 'SS': // 毫秒二位
                    var m = d.getMilliseconds();
                    if (m > 99) m = Math.round(m / 10);
                    return zeroize(m);
                case 'S': // 毫秒一位
                    return d.getMilliseconds();
                case 'aa': // 上午下午小写
                    return d.getHours() < 12 ? 'am' : 'pm';
                case 'AA': // 上午下午大写
                    return d.getHours() < 12 ? 'AM' : 'PM';
                case 'ZZ': // 时区
                    return d.toUTCString().match(/[A-Z]+$/);
                case 'q': // 数字季度
                    return Math.floor((d.getMonth() + 3) / 3);
                case 'qq': // 数字季度
                    return zeroize(Math.floor((d.getMonth() + 3) / 3));
                case 'Q': // 大写季度
                    return ['一', '二', '三', '四'][Math.floor((d.getMonth() + 3) / 3) - 1];
                case 'w': // 大写季度
                    return ['7', '1', '2', '3', '4', '5', '6'][d.getDay()];
                case 'ww': // 大写季度
                    return ['07', '01', '02', '03', '04', '05', '06'][d.getDay()];
                case 'W': // 大写季度
                    return ['日', '一', '二', '三', '四', '五', '六'][d.getDay()];
                default:
                    return $0.substr(1, $0.length - 2);
            }
        });
    };
};