js时间格式化输出

//输入:
formatDate(new Date(1409894060000), 'yyyy-MM-dd HH:mm:ss 星期w')
//输出:
2014-09-05 13:14:20 星期五
function formatDate(t,str){
  var obj = {
    yyyy:t.getFullYear(),
    yy:(""+ t.getFullYear()).slice(-2),
    M:t.getMonth()+1,
    MM:("0"+ (t.getMonth()+1)).slice(-2),
    d:t.getDate(),
    dd:("0" + t.getDate()).slice(-2),
    H:t.getHours(),
    HH:("0" + t.getHours()).slice(-2),
    h:t.getHours() % 12,
    hh:("0"+t.getHours() % 12).slice(-2),
    m:t.getMinutes(),
    mm:("0" + t.getMinutes()).slice(-2),
    s:t.getSeconds(),
    ss:("0" + t.getSeconds()).slice(-2),
    w:['日', '一', '二', '三', '四', '五', '六'][t.getDay()]
  };
  return str.replace(/([a-z]+)/ig,function($1){return obj[$1]});
}

function formatDate(date, format) {
    let hours =  date.getHours();
    let keyMap = {
        "y": date.getFullYear(),
        "M": date.getMonth()+1,
        "d": date.getDate(),
        "H": hours,
        "h": hours > 12 ?  hours -12 : hours,
        "m": date.getMinutes(),
        "s": date.getSeconds(),
        "w": date.getDay(),
    };
    
    Object.keys(keyMap).forEach((key) => {
        format = format.replace(new RegExp(`${key}+`, "g"), function(s){
            let value  = String(keyMap[key]);
            if(key === "y"){
                return  ("0000"+value).slice(-s.length);
            }
            return key === "w"   ? "日一二三四五六"[value] : ("00"+value).slice(-Math.max(value.length, s.length));
        })
    })
    
    return format;
}
unction formatDate(oDate, sFormation) {
    var obj={
        yyyy: oDate.getFullYear(),
        yy: oDate.getFullYear()%100,
        M: oDate.getMonth()+1,
        d: oDate.getDate(),
        H: oDate.getHours(),
        h: oDate.getHours()%12,
        m: oDate.getMinutes(),
        s: oDate.getSeconds(),
        w: ['日', '一', '二', '三', '四', '五', '六'][oDate.getDay()]
    };
    return sFormation.replace(/([a-zA-Z]+)/g,function($1){
        return $1.length===2&&$1!=='yy' ? ('0'+obj[$1.slice(1)]).slice(-2) : obj[$1];
    });
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值