Javascript Date对象格式化

Date.prototype.format = function (fmt) {
    var o = {
        "y+": this.getFullYear(), //年
        "M+": this.getMonth() + 1, //月
        "d+": this.getDate(), //日
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时(12小时制)
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    var week = {
        "0": "日",
        "1": "一",
        "2": "二",
        "3": "三",
        "4": "四",
        "5": "五",
        "6": "六"
    };
    if (arguments.length == 0) {
        fmt = "yyyy-MM-dd HH:mm:ss";
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + 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(-1 * RegExp.$1.length)));
        }
    }
    return fmt;
}

调用示例:

document.write(new Date().format()); //2013-07-04 22:11:57
document.write(new Date().format("yyyy-MM-dd E HH:mm:ss")); //2013-07-04 四 22:11:57
document.write(new Date().format("yyyy-MM-dd EE HH:mm:ss")); //2013-07-04 周四 22:11:57
document.write(new Date().format("yyyy-MM-dd EEE HH:mm:ss")); //2013-07-04 星期四 22:11:57
document.write(new Date().format("yy-M-d H:m:s.S")); //13-7-4 22:11:57.265

资料参考

[1].javascript Date format:http://blog.csdn.net/vbangle/article/details/5643091

评论: 0 | 引用: 0 | 查看次数: 3735
发表评论
登录后再发表评论!