首页 > 试题广场 >

时间格式化输出

[编程题]时间格式化输出
  • 热度指数:35449 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
按所给的时间格式输出指定的时间
格式说明
对于 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 结果为 五
示例1

输入

formatDate(new Date(1409894060000), 'yyyy-MM-dd HH:mm:ss 星期w')

输出

2014-09-05 13:14:20 星期五
function formatDate(d, format) {
    var year = d.getFullYear(),
        month = d.getMonth()+1,
        date = d.getDate(),
        hour = d.getHours(),
        minute = d.getMinutes(),
        second = d.getSeconds(),
        day = d.getDay(),
        week = ['日', '一', '二', '三', '四', '五', '六'];
    return format.replace(/yyyy/, year)
    				.replace(/yy/, pad(year % 100))
    				.replace(/MM/, pad(month))
    				.replace(/M/, month)
    				.replace(/dd/, pad(date))
    				.replace(/d/, date)
    				.replace(/HH/, pad(hour))
    				.replace(/H/, hour)
    				.replace(/hh/, pad(hour % 12))
    				.replace(/h/, hour % 12)
    				.replace(/mm/, pad(minute))
    				.replace(/m/, minute)
    				.replace(/ss/, pad(second))
    				.replace(/s/, second)
    				.replace(/w/, week[day]);
}

function pad(n){
    return n < 10 ? '0' + +n : n;
}

发表于 2015-09-29 21:31:10 回复(6)
function formatDate(t,str){
  var obj = {
    yyyyyyyy:t.getFullYear(),
    yy:t.getFullYear(),
    MM:t.getMonth()+1,
    dd:t.getDate(),
    HH:t.getHours(),
    hh:t.getHours() % 12,
    mm:t.getMinutes(),
    ss:t.getSeconds(),
    ww:['日', '一', '二', '三', '四', '五', '六'][t.getDay()]
  };
  return str.replace(/([a-z]+)/ig,function($1){
      //$1是yyyy的时候yyyyyyyy有效,不会进入补零操作,w同理
      return (obj[$1+$1]===0?'0':obj[$1+$1])||('0'+obj[$1]).slice(-2);
  });
}

编辑于 2017-03-09 18:47:44 回复(1)
function formatDate(oDate, sFormation) {
    var arr=[],brr=[],crr=[];
    arr=(sFormation.split(" "));
    brr=arr[0].split("-");
    crr=arr[1].split(":");
    var yFormat=brr[0];
    var MFormat=brr[1];
    var dFormat=brr[2];
    var hFormat=crr[0];
    var mFormat=crr[1];
    var sFormat=crr[2];
    
    var now=oDate;
    var Y=now.getFullYear()+"";
    var M=now.getMonth()+1+""; // caution 0-11
    var D=now.getDate()+"";
    var W=now.getDay()+"";
    var h=now.getHours()+"";
    var m=now.getMinutes()+"";
    var s=now.getSeconds()+"";
    
    var formatTwo=function (str,val) {
        val=str.length==2?(val=val<10?"0"+val:val):val;
        return val;
    };
    var weekFormat=function (week) {
        var wrr=["日","一","二","三","四","五","六"];
        return wrr[week];
    };
    Y=yFormat.length==4?Y:Y.substr(2,2);
    M=formatTwo(MFormat,M);
    D=formatTwo(dFormat,D);
    W=weekFormat(W);
    h=hFormat.indexOf("h")!=-1?h-12+"":h;
    h=formatTwo(hFormat,h);
    m=formatTwo(mFormat,m);
    s=formatTwo(sFormat,s);
    return Y+"-"+M+"-"+D+" "+h+":"+m+":"+s+" 星期"+W;
}

发表于 2016-08-01 22:52:32 回复(0)
        正则表达式加replace是真的用不明白
        function formatDate(oDate, sFormation) {
            var yyyy = oDate.getFullYear(),
                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('yyyy', yyyy)
                .replace('MM', addZero(M))
                .replace('dd', addZero(d))
                .replace('HH', addZero(H))
                .replace('hh', addZero(h))
                .replace('mm', addZero(m))
                .replace('ss', addZero(s))
                //需要分两种情况 两个字母表示小于10 需要补0 一个字母不需要补0
                .replace('yy', addZero(yyyy % 100))
                .replace('M', M)
                .replace('d', d)
                .replace('H', H)
                .replace('h', h)
                .replace('m', m)
                .replace('s', s)
                .replace('w', w)
        }
        function addZero(num) {
            return num > 9 ? num : '0' + num;
        }
发表于 2022-04-20 17:22:46 回复(0)
function formatDate(t, str) {
    let obj = {
        yyyy:t.getFullYear(),
        yy:(""+t.getFullYear()).slice(-2),
        MM:("0" + (t.getMonth() + 1)).slice(-2),
        M:t.getMonth()+1,
        dd:("0" + t.getDate()).slice(-2),
        d: t.getDate(),
        HH:('0' + t.getHours()).slice(-2),
        H:t.getHours(),
        hh:('0' + (t.getHours()%12)).slice(-2),
        h: t.getHours()%12,
        mm:('0'+t.getMinutes()).slice(-2),
        m:t.getMinutes(),
        ss:('0'+t.getSeconds()).slice(-2),
        s:t.getSeconds(),
        w:['日', '一', '二', '三', '四', '五', '六'][t.getDay()]
    };
    return str.replace(/([a-z]+)/ig,function($1){return obj[$1]});
}

发表于 2022-03-26 17:17:38 回复(0)
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()]
    };
    const reg = /y{2,4}|m{1,2}|d{1,2}|h{1,2}|s{1,2}|w/ig;
    return str.replace(reg, k => obj[k]);
}

发表于 2021-07-28 15:03:04 回复(0)
function formatDate(dateTime,format){

    const weeks =  ['日', '一', '二', '三', '四', '五', '六']

    return format.replace("yyyy",dateTime.getFullYear().toString().padStart(4,"0"))
                 .replace("MM",(dateTime.getMonth()+1).toString().padStart(2,"0"))
                 .replace("dd",dateTime.getDate().toString().padStart(2,"0"))
                 .replace("HH",dateTime.getHours().toString().padStart(2,"0"))
                 .replace("hh",(dateTime.getHours() - 12).toString().padStart(2,"0"))
                 .replace("mm",dateTime.getMinutes().toString().padStart(2,"0"))
                 .replace("ss",dateTime.getSeconds().toString().padStart(2,"0"))
                 .replace("w",weeks[dateTime.getDay()])
                 
}

为什么会报错呢

const formatDate =(dateTime,format) => {

    const weeks =  ['日', '一', '二', '三', '四', '五', '六']

    const padStart = n => n < 10?'0' + n.toString() : n


    return format.replace("yyyy",padStart(dateTime.getFullYear()))
                 .replace("yy",dateTime.getFullYear().toString().slice(-2))
                 .replace("MM",padStart(dateTime.getMonth()+1))
                 .replace("M",(dateTime.getMonth()+1).toString())
                 .replace("dd",padStart(dateTime.getDate()))
                 .replace("d",dateTime.getDate().toString())
                 .replace("HH",padStart(dateTime.getHours()))
                 .replace("H",dateTime.getHours().toString())
                 .replace("hh",padStart((dateTime.getHours()>12?dateTime.getHours() -12 : dateTime.getHours())))
                 .replace("h",(dateTime.getHours()>12?dateTime.getHours() -12 : dateTime.getHours()).toString())
                 .replace("mm",padStart(dateTime.getMinutes()))
                 .replace("m",dateTime.getMinutes().toString())
                 .replace("ss",padStart(dateTime.getSeconds()))
                 .replace("s",dateTime.getSeconds().toString())
                 .replace("w",weeks[dateTime.getDay()])
                 
}

利用string 的replace属性,这里不支持string pasStart 需要自己来写padStart
编辑于 2021-03-31 16:12:40 回复(1)
function formatDate (date, format) {
            let result = format.replace(/(y{1,4})/g, (match, $1) => {
                var year = date.getFullYear();
                return (year + '').slice(4 - $1.length)
            }).replace(/(M{1,2})/g, (match, $1) => {
                var month = String(date.getMonth() + 1) ;
                return $1.length === 2 ? (month.length === 1 ? '0' + month : month) : month;
            }).replace(/(d{1,2})/g, (match, $1) => {
                var day = date.getDate() + '';
                return $1.length === 2 ? (day.length === 1 ? '0' + day : day) : day;
            }).replace(/(h{1,2})/ig, (match, $1) => {
                var hour = (date.getHours()) + '';
                return $1.length === 2 ? (hour.length === 1 ? '0' + hour : hour) : hour
            }).replace(/(m{1,2})/g, (match, $1) => {
                var min = (date.getMinutes()) + '';
                return $1.length === 2 ? (min.length === 1 ? '0' + min : min) : min
            }).replace(/(s{1,2})/g, (match, $1) => {
                var s = (date.getSeconds()) + '';
                return $1.length === 2 ? (s.length === 1 ? '0' + s : s) : s
            }).replace(/(w)/g, (match, $1) => {
                var s = date.getDay();
                var day = ["日", "一", "二", "三", "四", "五", "六"]
                return day[s]
            })
            return result
        }
发表于 2021-02-28 12:59:15 回复(0)
function formatDate(dateObject, format) {
    function lessThan10ZeroPadding(num){
        if(num < 10) { return "0" + num.toString() }
        return num.toString()
    }
    let dictionary = {
        yyyy: dateObject.getFullYear().toString(),
        yy: dateObject.getFullYear().toString().slice(2),
        MM: lessThan10ZeroPadding(dateObject.getMonth() + 1),
        M: (dateObject.getMonth() + 1).toString(),
        dd: lessThan10ZeroPadding(dateObject.getDate()),
        d: dateObject.getDate().toString(),
        HH: lessThan10ZeroPadding(dateObject.getHours()),
        H: dateObject.getHours().toString(),
        hh: lessThan10ZeroPadding(dateObject.getHours() % 12),
        h: dateObject.getHours() % 12,
        mm: lessThan10ZeroPadding(dateObject.getMinutes()),
        m: dateObject.getMinutes().toString(),
        ss: lessThan10ZeroPadding(dateObject.getSeconds()),
        s: dateObject.getSeconds().toString(),
        w: (function(){
            let day = dateObject.getDay()
            week = {0:"日", 1:"一", 2:"二", 3:"三", 4:"四", 5:"五", 6:"六"}
            return week[day]
        }())
    }

    for(let key of Object.keys(dictionary)){
        format = format.replace(key, dictionary[key])
    }

    return format
}


编辑于 2020-06-07 10:54:06 回复(0)
function formatDate(myDate,str) {
        var yyyy = myDate.getFullYear().toString();
        var yy = yyyy.slice(2);
        var M = myDate.getMonth()+1;
        if (M < 10) {
            var MM = "0"+M;
        }
        var d = myDate.getDate();
        if (d < 10) {
            var dd = "0"+d;
        }else{
            dd = d;
        }
        var H = myDate.getHours();
        if (H < 10) {
            var HH = "0"+H;
        }
        else{
            HH = H;
        }
        var h = H%12;
        if (h < 10) {
            var hh = "0"+h;
        }
        else{
            hh = h;
        }
        var m = myDate.getMinutes();
        if (m < 10) {
            var mm = "0"+m;
        }
        else{
            mm = m;
        }
        var s = myDate.getSeconds();
        if (s < 10) {
            var ss = "0"+s;
        }
        else{
            ss = s;
        }
        var day = myDate.getDay();
        var w = ['日', '一', '二', '三', '四', '五', '六'][day];
    
        var rstr1 = str.replace(/-/g,"+'-'+");
        var rstr2 = rstr1.replace(/\s/g,"+' '+");
        var rstr3 = rstr2.replace(/:/g,"+':'+");
        var rstr4 = rstr3.replace(/[\u4E00-\u9FA5]+/,"'星期'+");

        eval("console.log("+rstr4+")")
    }
在自己的电脑上调试可以通过,但是却通过不了,大概是因为我的方法太笨了😅😅
发表于 2019-09-20 19:58:09 回复(0)
function formatDate(date,fmt){
        var o={
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "H+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds(), //秒
        }
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));//年
        if (/(w+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (['日', '一', '二', '三', '四', '五', '六'][date.getDay()]));//周几
        if (/(h+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o['H+']%12) : (("0"+o['H+']%12).slice(-2)));//12小时制
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("0"+o[k]).slice(-2)));
        return fmt;
    }
发表于 2018-12-31 10:57:20 回复(0)
function formatDate(oDate, sFormation) {
    if (Object.prototype.toString.call(oDate) !== '[object Date]') {
    	oDate = new Date(oDate)
    }

    var Day = ['日', '一' , '二', '三', '四', '五', '六']
    var o = {
    	'y' : oDate.getFullYear(),
    	'M' : oDate.getMonth() + 1,
    	'd' : oDate.getDate(),
    	'H' : oDate.getHours(),
    	'h' : oDate.getHours() > 12 ? oDate.getHours() - 12 : oDate.getHours(),
    	'm' : oDate.getMinutes(),
    	's' : oDate.getSeconds(),
    	'w' : Day[oDate.getDay()]
    }

    return sFormation.replace(/\w+/g, function(str) {
    	var s = str.slice(0, 1)
    	var formatStr = o[s]

    	// 年份
    	if (s === 'y' && str.length === 2) {
    		formatStr = ('' + formatStr).slice(2,4)
    	} else if (str.length === 2) {
    		formatStr = formatStr < 10 ? '0' + formatStr : '' + formatStr
    	}

    	return formatStr
    })
}
本地运行正常,不知道牛客网上哪里错了
发表于 2017-09-10 11:46:21 回复(0)
function formatDate(oDate, sFormation) {
    var yyyy = oDate.getFullYear();
    var yy = yyyy.toString().substr(2);
    var M = (oDate.getMonth()+1).toString();
    var MM = M.length == 1?'0'+M:M;
    var d = oDate.getDate().toString();
    var dd = d.length == 1?'0'+d:d;
    var H =oDate.getHours().toString();
    var HH = H.length == 1?'0'+H:H;
    var h = H>12?(0+H-12).toString():H;
    var hh = h.length == 1?'0'+h:h;
    var m = oDate.getMinutes().toString();
    var mm = m.length == 1?'0'+m:m;
    var s = oDate.getSeconds().toString();
    var ss = s.lengh == 1?'0'+s:s;
    var wArray = ['日','一','二','三','四','五','六'];
    var week = oDate.getDay();
    var w = wArray[week];
 var newDateObj = {
  yyyy:yyyy,
  yy:yy,
  M:M,
  MM:MM,
  d:d,
  dd:dd,
  H:H,
  HH:HH,
  h:h,
  hh:hh,
  m:m,
  mm:mm,
  s:s,
  ss:ss,
  w:w
 };
    var result = sFormation.replace(/[a-z]+/ig,function($1){return newDateObj[$1];});
 return result;
}

发表于 2015-08-24 08:38:28 回复(2)
虽然方法笨,但是绝对能通过:
function formatDate(times, format) {
    let date = times
    let year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate(),
        hours = date.getHours(),
        minutes = date.getMinutes(),
        seconds = date.getSeconds(),
        w = date.getDay()
    function addZero(str, t) {
        format = format.replace(str, t < 10 ? '0' + t : t)
        format = format.replace(str[0], t)
    }
    format = format.replace('yyyy', year)
    format = format.replace('yy', year % 100)
    addZero('MM', month)
    addZero('dd', day)
    addZero('HH', hours)
    format = format.replace('hh', hours > 12 ? '0' + (hours - 12) : '0' + hours)
    format = format.replace('h', hours > 12 ? hours - 12 : hours)
    addZero('mm', minutes)
    addZero('ss', seconds)
    w = ['日', '一', '二', '三', '四', '五', '六'][w]
    format = format.replace('w', w)
    return format      
}


发表于 2021-07-20 15:12:40 回复(0)
function zeroize(n) {
    return Number(n) >= 10 ? n : '0' + n 
}
function formatDate(date, format) {
    let y = date.getFullYear()
    let obj = {
        M: date.getMonth() + 1, // 0 ~ 11
        d: date.getDate(), // 1 ~ 31
        H: date.getHours(), // 0 ~ 23
        h: date.getHours() % 12,
        m: date.getMinutes(), // 0 ~ 59
        s: date.getSeconds(), // 0 ~ 59
        w: ['日', '一', '二', '三', '四', '五', '六'][date.getDay()]    // 0 ~ 6
    }
    format = format.replace(/yy(yy)?/, (_, v) =>  v ?  y : (y+'').slice(-2))
    for (let key in obj) {
       format = format.replace(new RegExp(`${key}(${key})?`), (_, v) => v ? zeroize(obj[key]) : obj[key])
    }
    return format
} 

编辑于 2019-11-09 00:49:15 回复(0)
javascript:
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]});
}
编辑于 2015-06-29 09:58:28 回复(36)
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 = sFormation.replace(k,o[k]);
    }
    return sFormation;
}

发表于 2015-10-08 12:47:30 回复(7)
//最简单的方式来啦!
function 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];
    });
}

发表于 2016-08-27 15:37:32 回复(2)
function formatDate(oDate, sFormation) {
    
    //获取当前事件
    var year = oDate.getFullYear();
    var month = oDate.getMonth() + 1;       //原0-11
    var day = oDate.getDate();
    var hours = oDate.getHours();        
    var minutes = oDate.getMinutes();   
    var seconds = oDate.getSeconds();  
    var w = oDate.getDay();
    var weeks = ['日', '一', '二', '三', '四', '五', '六'];
    
    //获取传递进来的格式,以空格分割 yyyy-MM-dd HH:mm:ss 星期w
    var time = sFormation.split(" ");
    //获取年月日格式,以-分割 yyyy MM dd
    var ymd = time[0].split("-");
    //获取时分秒格式,以:分割 HH mm ss
    var hms = time[1].split(":");
    
    //判断输出的年份格式
    switch(ymd[0]) {
        case "yyyy": 
            year;
            break;
            
        case"yy":
            year = year % 100;
            break;
            
        default:
            alert("格式错误,请重新输入");
    }
    
    //判断输出的月份格式
    switch(ymd[1]) {
        case "MM": 
            if(month < 10) {
                month = "0" + month;
            }
            break;
            
        case"M":
            month;
            break;
            
        default:
            alert("格式错误,请重新输入");
    }
    
    //判断输出的日期格式
    switch(ymd[2]) {
        case "dd": 
            if(day < 10) {
                day = "0" + day;
            }
            break;
            
        case"d":
            day;
            break;
            
        default:
            alert("格式错误,请重新输入");
    }
    
    //判断输出的小时格式
    switch(hms[0]) {
        case "HH": 
            hours;
            break;
            
        case"H":
            hours -= 12;
            if(hours < 10) {
                hours = "0" + hours;
            }
            break;
            
        default:
            alert("格式错误,请重新输入");
    }
    
    //判断输出的分钟格式
    switch(hms[1]) {
        case "mm": 
            if(minutes < 10) {
                minutes = "0" + minutes;
            }
            break;
            
        case"m":
            minutes;
            break;
            
        default:
            alert("格式错误,请重新输入");
    }
    
    //判断输出的秒钟格式
    switch(hms[2]) {
        case "ss": 
            if(seconds < 10) {
                seconds = "0" + seconds;
            }
            break;
            
        case"s":
            seconds;
            break;
            
        default:
            alert("格式错误,请重新输入");
    }
    
    //输出星期
    var week = time[2].replace("w",weeks[w]);
    
    //整合信息
    var sysWeeks = year + "-" + month + "-" + day + " " 
    + hours + ":" + minutes + ":" + seconds + " " 
    + week;
    
    return sysWeeks;
}

//测试代码
var data = new Date();
console.log(formatDate(data, 'yyyy-MM-dd HH:mm:ss 星期w'));

这个代码在本机运行可以,但是在该网站上报错(估计是太长了)。这个是用的最笨的方法,我一开始也用的评论大神的一些代码,但是都通过不了,于是自己写一个笨的代码(其实是人笨,不会写简单的)。代码很长但是都是重复的内容,这些内容是可以整个的。代码非常好懂,供大家参考。
发表于 2017-09-20 17:05:06 回复(1)
给最高赞热评的答案加了一些注释
// FED7时间格式化输出

// 描述
// 按所给的时间格式输出指定的时间
// 格式说明
// 对于 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 结果为 五

// 示例1
// 输入:
// 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(),
        // getFullYear() 方法可返回一个表示年份的 4 位数字
        yy: ("" + t.getFullYear()).slice(-2),
        // 数字无slice方法,用空字符串""与之进行+运算
        // 使其变成字符串类型然后使用slice方法,可用以下代码代替
        // yy:t.getFullYear().toString(10).slice(-2),
        M: t.getMonth() + 1,
        // getMonth() 方法可返回表示月份的数字
        // 返回值是0(一月)到11(十二月)之间的一个整数
        MM: ("0" + (t.getMonth() + 1)).slice(-2),
        // 如("0"+1).slice(-2)  返回字符串"01"
        // 如("0"+12).slice(-2)  返回字符串"12"
        d: t.getDate(),
        // 从 Date 对象返回一个月中的某一天 (1 ~ 31)
        dd: ("0" + t.getDate()).slice(-2),
        H: t.getHours(),
        // 返回 Date 对象的小时 (0 ~ 23)
        HH: ("0" + t.getHours()).slice(-2),
        h: t.getHours() % 12,
        hh: ("0" + t.getHours() % 12).slice(-2),
        m: t.getMinutes(),
        // 返回 Date 对象的分钟 (0 ~ 59)
        mm: ("0" + t.getMinutes()).slice(-2),
        s: t.getSeconds(),
        // 返回 Date 对象的秒数 (0 ~ 59)
        ss: ("0" + t.getSeconds()).slice(-2),
        w: ['日', '一', '二', '三', '四', '五', '六'][t.getDay()]
            // 从 Date 对象返回一周中的某一天 (0(周天) ~ 6(周六)
            // 把['日',.., '六']看做一个数组arr
            // 属性w的值为arr[0]~arr[6]
    };
    return str.replace(/([a-z]+)/ig, function($1) { return obj[$1] });
}


发表于 2021-08-11 17:52:53 回复(0)