JavaScript处理日期格式化

Date.prototype.toString = function (format) {
    if (format == null) {
        format = "yyyy-MM-dd HH:mm:ss";
    }

    format = format.replace(/yyyy/g, this.getFullYear());
    format = format.replace(/yyy/g, this.getYear());
    format = format.replace(/yy/g, this.getFullYear().toString().slice(-2));

    if (format.indexOf('mi') >= 0) {
        format = format.replace(/mi/g, this.getMilliseconds().toString());
    }

    if (format.indexOf('M') >= 0) {
        var M = (this.getMonth() + 1).toString();
        format = format.replace(/MM/g, ("0" + M).slice(-2));
        format = format.replace(/M/g, M);
    }

    if (format.indexOf('ddd') >= 0) {
        var xq = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"];
        format = format.replace(/ddd/g, xq[this.getDay()]);
    }

    if (format.indexOf('d') >= 0) {
        var d = this.getDate().toString();
        format = format.replace(/dd/g, ("0" + d).slice(-2));
        format = format.replace(/d/g, d);
    }


    if (format.indexOf('h') >= 0 || format.indexOf('H') >= 0) {
        var h = this.getHours();
        format = format.replace(/HH/g, ("0" + h.toString()).slice(-2));
        format = format.replace(/H/g, h);
        h = h % 12;
        format = format.replace(/hh/g, ("0" + h.toString()).slice(-2));
        format = format.replace(/h/g, h);
    }

    if (format.indexOf('m') >= 0) {
        var m = this.getMinutes().toString();
        format = format.replace(/mm/g, ("0" + m).slice(-2));
        format = format.replace(/m/g, m);
    }

    if (format.indexOf('s') >= 0) {
        var s = this.getSeconds().toString();
        format = format.replace(/ss/g, ("0" + s).slice(-2));
        format = format.replace(/s/g, m);
    }



    return format;
}
使用方式:
var t_date=new Date();
alert(t_date.toString()); //2014-05-09 05:12:31
alert(t_date.toString('yyyy/MM/dd'))//2014/05/09
alert(t_date.toString('HH:mm:ss'));//05:12:31
alert(t_date.toString(HH:mm:ss.mi));//05:12:31.332



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值