时间格式化输出

题目描述

按所给的时间格式输出指定的时间
格式说明
对于 2014.09.05 13:14:20
yyyy: 年份,2014
yy: 年份,14
MM: 月份,补满两位,09
M: 月份, 9
dd: 日期,补满两位,05
d: 日期, 5
HH: 24制小时,补满两位,13
H: 24制小时,13
hh: 12制小时,补满两位,01
h: 12制小时,1
mm: 分钟,补满两位,14
m: 分钟,14
ss: 秒,补满两位,20
s: 秒,20
w: 星期,为 ['日', '一', '二', '三', '四', '五', '六'] 中的某一个,本 demo 结果为 五

function formatDate(oDate, sFormation) {
    var add0 = function(num){
        if(num<10)
            return 0+""+num;
        else
            return num;
 
    };
    var o = {
        "yyyy":oDate.getFullYear(),
        "yy":oDate.getFullYear()%100,  //年份的后两位
        "MM":add0(oDate.getMonth()+1),
        "M":oDate.getMonth()+1,
        "dd":add0(oDate.getDate()),
        "d":oDate.getDate(),
        "HH":add0(oDate.getHours()),
        "H":oDate.getHours(),
        "hh":add0(oDate.getHours()%12),
        "h":oDate.getHours()%12,
        "mm":add0(oDate.getMinutes()),
        "m":oDate.getMinutes(),
        "ss":add0(oDate.getSeconds()),
        "s":oDate.getSeconds(),
        "w":function(){
            var day = ["日","一","二","三","四","五","六"];
            return day[oDate.getDay()];
        }(),
    };
    for(var k in o){  //sFormation中是否含有k字符串
        sFormation = sFormation.replace(k,o[k]);
    }
    return sFormation;
}
alert(formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss 星期w'));

 

来源:牛客网

猜你喜欢

转载自www.cnblogs.com/daheiylx/p/8981094.html