首页 > 试题广场 >

时间格式化输出

[编程题]时间格式化输出
  • 热度指数:36639 时间限制: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 结果为 五

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


输出描述:
2014-09-05 13:14:20 星期五
示例1

输入

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

输出

2014-09-05 13:14:20 星期五
function addZero(func){
    return func > 9 ? func : '0' + func
}

function formatDate(time, format) {
    let obj = {
        yyyy: () => time.getFullYear(),
        yy: () => time.getFullYear()%100,
        MM: () => addZero(time.getMonth()+1),
        M: () => time.getMonth()+1,
        dd: () => addZero(time.getDate()),
        d: () => time.getDate(),
        HH: () => addZero(time.getHours()),
        H: () => time.getHours(),
        hh: () => addZero(time.getHours() % 12),
        h: () => time.getHours() % 12,
        mm: () => addZero(time.getMinutes()),
        m: () => time.getMinutes(),
        ss: () => addZero(time.getSeconds()),
        s: () => time.getSeconds(),
        w: () => ['日', '一', '二', '三', '四', '五', '六'][time.getDay()]
    }
    for(const k in obj) {
        format = format.replace(k, obj[k]())
    }
    return format
}
发表于 2021-06-03 21:18:44 回复(0)
    function formatDate(date, fmt) {
      // y+ -> 1个或者多个y
      //y* -> 0个或者多个y
      //y? -> 0个或者1个y
      //1.获取年份
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'H+': date.getHours(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
        }
      }
      let w = new Date(date).getDay();
      if (w == '0') w = '日';
      if (w == '1') w = '一';
      if (w == '2') w = '二';
      if (w == '3') w = '三';
      if (w == '4') w = '四';
      if (w == '5') w = '五';
      if (w == '6') w = '六';
      fmt = fmt.replace('w', w);
      return fmt;
    };

    // 04:04:04
    function padLeftZero(str) {
      return ('00' + str).substr(str.length);
    };

发表于 2021-05-10 20:11:04 回复(0)
为啥我这个通过不了,哎
function formatDate(date, fmt) {
    const weeks = ['日', '一', '二', '三', '四', '五', '六'] 
    const map = {
        'y+': date.getFullYear(),
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'H+': date.getHours(),
        'h+': date.getHours() % 12,
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'w': weeks[date.getDay()]
    }
    for (const key in map) {
        if (Object.prototype.hasOwnProperty.call(map, key)) {
            fmt = fmt.replace(new RegExp(key), (a, b, c) => {
                const target = String(map[key]);
                if (a.length < target.length && a.length >= 2) {
                    return target.substr(-a.length);
                }
                return target.padStart(a.length, '0');
            });
        }
    }
    return fmt;
}


发表于 2021-05-10 09:47:57 回复(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(t,str){
    var oo = {
        yyyy:t.getFullYear(),
        yy:t.(""+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:function(){
            var day = ['日', '一', '二', '三', '四', '五', '六'];
            return day[t.getDay()];
        }
    };
    for(var m in oo){
        str = str.replace(m,oo[m]);
    }
    return str;
}
我不知道我哪里错了,希望有大佬指教一下,有点搞不懂了
发表于 2021-01-29 12:39:36 回复(2)
相对比较好理解,定义两个对象,
第一个对象 dateObj1 存放比较长的匹配,比如,yyyy,MM,dd...,
一个对象 dateObj2 存放比较短的匹配,比如,yy,M,d,H...,
然后遍历对象,去和格式化表达式进行匹配,包含( indesOf() )则替换( replace() )

需要注意,必须先遍历长规则的匹配对象,再遍历短规则的匹配对象,原因很简单,因为 yy 包含在 yyyy 中,代码如下:
function formatDate(time, reg){
    let res = reg;
    let dateObj1 = {
        yyyy: time.getFullYear(),
        MM: set0(time.getMonth()+1),
        dd: set0(time.getDay()),
        HH: set0(time.getHours()),
        hh: time.getHours()>12?set0(time.getHours()-12):set0(time.getHours()),
        mm: set0(time.getMinutes()),
        ss: set0(time.getSeconds()),
        w: '日一二三四五六'.charAt(time.getDate())
    };
    let dateObj2 = {
        yy: (''+time.getFullYear()).substr(2),
        M: time.getMonth()+1,
        d: time.getDay(),
        H: time.getHours(),
        h: time.getHours()>12?time.getHours()-12:time.getHours(),
        m: time.getMinutes(),
        s: time.getSeconds()
    }
    for(let i=1;i<3;i++){
        let obj = dateObj1;
        if(i==2){
            obj = dateObj2;
        }
        
        for(let item in obj){
            if(res.indexOf(item)!=-1){
                res = res.replace(item,obj[item]);
            }
        }
    }
    return res;
    
    function set0(str){
        let res = '' + str;
        if(res.length===1){
            res = '0' + res;
        }
        return res;
    }
    
}


编辑于 2020-05-03 19:25:21 回复(0)
function formatDate(date, format){
    let weekList = ['日', '一', '二', '三', '四', '五', '六'];
    let year  = date.getFullYear() + "";
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hours = date.getHours();
    let hh = hours >= 12 ? hours - 12 : hours;
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    let resObj = {
        yyyy: year,
        yy: year.slice(-2),
        MM: month <= 9 ? `0${month}` : month,
        M: month,
        dd: day <= 9 ? `0${day}` : day,
        d: day,
        HH: hours <= 9 ? `0${hours}` : hours,  // 24小时制 补零
        H: hours,
        hh: hh <= 9 ? `0${hh}` : hh,
        h: hh,
        mm: minutes <= 9 ? `0${minutes}` : minutes,
        m: minutes,
        ss: seconds <= 9 ? `0${seconds}` : seconds,
        s: seconds,
        w: weekList[date.getDay()]
    };

    return Object.keys(resObj).reduce((prev, next) => {
        return prev.replace(next, resObj[next]);
    }, format);
};

发表于 2019-09-30 11:42: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)
为什么本地测试可以通过,但是编译不过
发表于 2017-08-12 10:27:18 回复(0)
有没有人能贴个能用的代码?为什么之前能通过的代码现在都通不过了?
发表于 2017-07-13 11:15:34 回复(1)
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)
我的方法稍稍有点啰嗦
首先取出new Date中的各个年月日等的值,然后再进行格式的“拼接”。
function formatDate(oDate, sFormation) {
    var year = oDate.getFullYear();
    var month = oDate.getMonth()+1;
    var day = oDate.getDate();
    var hour = oDate.getHours();
    var minutes = oDate.getMinutes();
    var seconds = oDate.getSeconds();
    var week = oDate.getDay();
    switch(week){
    case 0:
    week = "日";break;
    case 1:
    week = "一";break;
    case 2:
    week = "二";break;
    case 3:
    week = "三";break;
    case 4:
    week = "四";break;
    case 5:
    week = "五";break;
    case 6:
    week = "六";break;
    }
    console.log( sFormation.replace(/yyyy/,year)
    .replace(/yy/,tool(year%100))
    .replace(/MM/,tool(month))
    .replace(/M/,month)
    .replace(/dd/,tool(day))
    .replace(/d/,day)
    .replace(/HH/,tool(hour))
    .replace(/H/,hour)
    .replace(/hh/,tool(hour%12))
    .replace(/h/,hour%12)
    .replace(/mm/,tool(minutes))
    .replace(/m/,minutes)
    .replace(/ss/,tool(seconds))
    .replace(/s/,seconds)
    .replace(/w/,week))
}
function tool(n){
return n<10?("0"+n):n;
}
发表于 2017-02-25 13:14:05 回复(0)
通过率 66.67%,好心塞,基础太差,不会正则,也不会用简洁的代码,把这个代码先放在这儿,
等我再打哈基础来再来。
function formatDate(oDate, sFormation) {
    var time = oDate.toString().split(" ")[4],
        year = oDate.getFullYear(),  // 2014
        month = oDate.getMonth()+1,    // 9
        date = oDate.getDate(),      // 2
        day = oDate.getDay();        // 5
    switch(day){
        case 0: day = "星期日"; break;
        case 1: day = "星期一"; break;
        case 2: day = "星期二"; break;
        case 3: day = "星期三"; break;
        case 4: day = "星期四"; break;
        case 5: day = "星期五"; break;
        case 6: day = "星期六"; break;
        default:
            break;
    }

    var format = sFormation.split(" ");
    var dateSplit = format[0].split("-");
    var timeSplit = format[1].split(":");

    //年
    if(dateSplit[0].length == 4){
        year = year.toString();
    }else if(dateSplit[0].length == 2){
        year = year.toString().substr(2,2);
    }

    //月
    if (dateSplit[1].length ==2 && month<10) {
        month ="0" + month.toString();
    }else{
        month = month.toString();
    }
    //日
    if( dateSplit[2].length == 2 && date<10){
        date = "0" + date.toString();
    }else{
        date = date.toString();
    }

    var hour = time.split(":")[0];
    var minute = time.split(":")[1];
    var second = time.split(":")[2];
    //  时
    if( (timeSplit[0].length==2) && (timeSplit[0].indexOf("H")!=-1) && hour<10 ){  // HH < 10 的情况
        hour = "0" + hour.toString();
    }else if( (timeSplit[0].length==2) && (timeSplit[0].indexOf("h")!=-1) ) { // hh 的情况
        if(hour<10)
            hour = "0" + hour.toString();
        if(hour>12)
            hour = "0" + (hour-12).toString();
    }else if( (timeSplit[0].length==1) && (timeSplit[0].indexOf("h")!=-1) ){  // h 的情况
        if(hour>12)
            hour = (hour-12).toString();
        else
            hour = hour.toString();
    }else{
        hour = hour.toString();
    }

    //分
    if(timeSplit[1].length==2 && minute<10){
        minute = "0" + minute.toString();
    }else{
        minute = minute.toString();
    }

    //秒
    if(timeSplit[2].length==2 && second<10){
        second = "0" + second.toString();
    }else{
        second = second.toString();
    }

    var dateStr = [year,month,date].join("-");
    var timeStr = [hour,minute,second].join(":");

    console.log([dateStr,timeStr,day].join(" "));
    return [dateStr,timeStr,day].join(" ");
}

发表于 2016-08-25 17:01:30 回复(0)

问题信息

难度:
13条回答 16667浏览

热门推荐

通过挑战的用户

查看代码
时间格式化输出