首页 > 试题广场 >

时间格式化输出

[编程题]时间格式化输出
  • 热度指数:35470 时间限制: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(date, format) {
    const weekChineseArr = [
      '日', '一', '二', '三', '四', '五', '六'
    ];
    const getTimeInfo = {
      yyyy: (date) => date.getFullYear(),
      yy: (date) => String(date.getFullYear()).slice(-2),
      MM: (date) => String(date.getMonth() + 1).padStart(2, '0'),
      M: (date) => (date.getMonth() + 1),
      dd: (date) => String(date.getDate()).padStart(2, '0'),
      d: (date) => date.getDate(),
      HH: (date) => String(date.getHours()).padStart(2, '0'),
      H: (date) => date.getHours(),
      hh: (date) => String((date.getHours() % 12) || 12).padStart(2, '0'),
      h: (date) => (date.getHours() % 12) || 12,
      mm: (date) => String(date.getMinutes()).padStart(2, '0'),
      m: (date) => date.getMinutes(),
      ss: (date) => String(date.getSeconds()).padStart(2, '0'),
      s: (date) => date.getSeconds(),
      w: (date) => weekChineseArr[date.getDay()], // 注意这里返回的是星期几的数字(0-6)
    };

    for (const f in getTimeInfo) {
        if(format.indexOf(f) !== -1) {
          const timeInfo = getTimeInfo[f](date);
          format = format.replace(f, timeInfo);      
        }
    }
    return format;
}

不明白为什么过不了??
发表于 2023-05-20 22:26:42 回复(0)
function formatDate(date, format) {
  function addZero(s) {
    return s < 10 ? ('0' + s) : s;
}
let obj = {
        'yyyy': date.getFullYear(),
        'yy': date.getFullYear() % 100,
        'MM': addZero(date.getMonth() + 1),
        'M':  date.getMonth() + 1,
        'dd': addZero(date.getDate()),
        'd':  date.getDate(),
        'HH': addZero(date.getHours()),
        'H': date.getHours(),
        'hh': addZero(date.getHours()>12?date.getHours()-12:date.getHours()),
        'h':  date.getHours()>12?date.getHours()-12:date.getHours(),
        'mm': addZero(date.getMinutes()),
        'm': date.getMinutes(),
        'ss': addZero(date.getSeconds()),
        's': date.getSeconds(),
        'w': function () {
            arr = ['日', '一', '二', '三', '四', '五', '六']
            return arr[date.getDay()]
        }()
    }

    for(key in obj){
      var format=format.replace(key,obj[key])
    }
    return format
}
发表于 2023-04-10 15:53:17 回复(0)
function formatDate(date, forMat) {
            try{
                const map = ['日', '一', '二', '三', '四', '五', '六']
            const y = date.getFullYear()
            const m = date.getMonth() + 1
            const day = date.getDate()
            const h = date.getHours()
            const min = date.getMinutes()
            const s = date.getSeconds()
            const day1 = date.getDay()
            function padZero(length, str) {
                str += ""
                if (length <= str.length) return str
                return padZero(length++, 0 + "" + str)
            }
            const ret = forMat
            return ret
                .replace(/yyyy/g, _ => y)
                .replace(/yy/g, _ => (y + '').substring(2))
                .replace(/MM/g, _ => padZero(2, m))
                .replace(/M/g, _ => m)
                .replace(/dd/g, _ => padZero(2, day))
                .replace(/d/g, day)
                .replace(/HH/g, _ => padZero(2, h))
                .replace(/H/g, _ => h)
                .replace(/hh/g, _ => padZero(2, h % 12))
                .replace(/h/g, _ => h % 12)
                .replace(/mm/g, _ => padZero(2, min))
                .replace(/m/g, _ => min)
                .replace(/ss/g, _ => padZero(2, s))
                .replace(/s/g, _ => s)
                .replace(/w/g, _ => map[day1])
            }catch(e){
                return e
            }
        }
发表于 2023-01-12 14:21:42 回复(0)
这不通过?
function formatDate(date, format) {
    let obj = {
        'yyyy': date.getFullYear(),
        'yy': date.getFullYear().toString().slice(2),
        'MM': date.getMonth() + 1 < 10 ? '0' + date.getMonth() + 1 : date.getMonth() + 1,
        'M': date.getMonth() + 1,
        'dd': date.getDate() < 10 ? '0' + date.getDate() : date.getDate(),
        'd': date.getDate(),
        'HH': date.getHours() < 10 ? '0' + date.getHours() : date.getHours(),
        'H': date.getHours(),
        'hh': date.getHours() % 12 < 10 ? '0' + date.getHours() % 12 : date.getHours() % 12,
        'h': date.getHours() % 12,
        'mm': date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(),
        'm': date.getMinutes(),
        'ss': date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(),
        's': date.getSeconds(),
        'w': function() {
            let arr = ['日', '一', '二', '三', '四', '五', '六'];
            return arr[date.getDay()];
        }
    }
    for (const key in obj) {
        format = format.replace(key, obj[key]);
    }
    return format;
}


发表于 2022-10-13 16:37:10 回复(0)
用笨办法终于写出来了
function zero(t){
    return t>9?t:('0'+t);
  }


function formatDate(date,formatTemplate){
	// = new Date(1409894060000);
	//='yyyy-MM-dd HH:mm:ss 星期w';
	let separator = /\-|\:|\ /;
    let arr = formatTemplate.split(separator);
	let arr2 = formatTemplate.match(/\-|\:|\ /g);
	
	 let f = '';
	 let week = '';
     let weekDay = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
	 
	 for(let i = 0;i<arr.length;i++){
		 if(arr[i] == 'yyyy'){
			 f += date.getFullYear();
		 }
		 if(arr[i] == 'yy'){
			 f += date.getFullYear().toString().substr(2, 2);
		 }
		 if(arr[i] == 'MM'){
			 f += arr2[i-1]+zero(date.getMonth()+1);
		 }
		 if(arr[i] == 'M'){
			 if((date.getMonth()+1) >= 10 ){
				 f += arr2[i-1]+zero(date.getMonth()+1);
			 }else{
			 f += arr2[i-1]+zero(date.getMonth()+1).toString().substr(1,1);
			 }
		 }
		 
		 if(arr[i] == 'dd'){	 
		 	 f += arr2[i-1]+zero(date.getDate());
		 }
		 if(arr[i] == 'd'){
			 if(date.getDate() >= 10 ){
			 	 f += arr2[i-1]+zero(date.getDate());
			 }else{
		 	f += arr2[i-1]+zero(date.getDate()).toString().substr(1,1);
			}
		 }
		 
		if(arr[i] == "HH" || arr[i] == "hh"){
			f += arr2[i-1]+zero(date.getHours());
		}
		
		if(arr[i] == "H" || arr[i] == "h"){
			if(date.getHours() >= 10 ){
				f += arr2[i-1]+zero(date.getHours());
			}else{
			f += arr2[i-1]+zero(date.getHours()).toString().substr(1,1);
			}
		}
		
		if(arr[i] == "mm"){
			f += arr2[i-1]+zero(date.getMinutes());
		}
		if(arr[i] == "m"){
			if(date.getMinutes() >= 10){
			    f += arr2[i-1]+zero(date.getMinutes());
			}else{
			  f += arr2[i-1]+zero(date.getMinutes()).toString().substr(1,1);
			}
		}
		
		if(arr[i] == "ss"){
			f += arr2[i-1]+zero(date.getSeconds());
		}
		
		if(arr[i] == "s"){
			if(date.getSeconds() >= 10){
				f += arr2[i-1]+zero(date.getSeconds());
			}else{
			f += arr2[i-1]+zero(date.getSeconds()).toString().substr(1,1);
			}
		}
		
		if(arr[i] == "星期w"){
			f += arr2[i-1]+weekDay[date.getDay()];
		}
		 
	 }
    return f;
}


发表于 2022-08-19 14:29:43 回复(0)
 function formatDate(date, str) {
        let format = new Map();
        let yyyy = date.getFullYear();
        let yy = +yyyy.toString().slice(-2);
        let MM = ('0000' + (date.getMonth() + 1)).slice(-2);
        let M = date.getMonth() + 1;
        let dd = ('0000' + date.getDate()).slice(-2);
        let d = date.getDate();
        let HH = ('0000' + date.getHours()).slice(-2);
        let H = date.getHours;
        let hh = ('0000' + (date.getHours() - 12)).slice(-2);
        let h = date.getHours() - 12;
        let mm = ('0000' + date.getMinutes()).slice(-2);
        let m = date.getMinutes();
        let ss = ('0000' + date.getSeconds()).slice(-2);
        let s = date.getSeconds();
        let w = ['天', '一', '二', '三', '四', '五', '六'][date.getDay()];
        format.set('yyyy', yyyy);
        format.set('yy', yy);
        format.set('MM', MM);
        format.set('M', M);
        format.set('dd', dd);
        format.set('d', d);
        format.set('HH', HH);
        format.set('H', H);
        format.set('hh', hh);
        format.set('h', h);
        format.set('mm', mm);
        format.set('m', m);
        format.set('ss', ss);
        format.set('s', s);
        format.set('w', w);
        let s1 = str.replaceAll(/(\w+)/g, (target) => {
          const res = format.get(target);
          return res;
        });
        return s1;
      }
本地好使,代码没通过,挂个代码表示写过

发表于 2022-07-18 15:26:03 回复(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(date, str) {
    let res = str
    let weeks = ['日', '一', '二', '三', '四', '五', '六']
    //   初始化时间属性对象
    let timeObj = {
        yyyy: date.getFullYear(),
        yy: date.getYear() % 100,
        M: date.getMonth() + 1,
        d: date.getDate(),
        H: date.getHours(),
        m: date.getMinutes(),
        s: date.getSeconds()
    }
    timeObj.MM = timeObj.M > 9 ? timeObj.M : '0' + timeObj.M
    timeObj.dd = timeObj.d > 9 ? timeObj.d : '0' + timeObj.d
    timeObj.HH = timeObj.H > 9 ? timeObj.H : '0' + timeObj.H
    timeObj.h = timeObj.H == 12 ? 12 : timeObj.H % 12
    timeObj.hh = timeObj.h > 9 ? timeObj.h : '0' + timeObj.h
    timeObj.mm = timeObj.m > 9 ? timeObj.m : '0' + timeObj.m
    timeObj.ss = timeObj.s > 9 ? timeObj.s : '0' + timeObj.s
    timeObj.w = weeks[date.getDay()]
    //   对象的键名排序,保证替换时不会先替换单字母,优先替换双字母
    let keyArr = Object.keys(timeObj)
    keyArr.sort((a, b) => (a < b ? 1 : -1))
    //   逐个替换
    for (let key of keyArr) {
        res = res.replace(key, timeObj[key])
    }
    return res
}

发表于 2021-12-05 04:53:11 回复(0)

function formatDate(date, format) {
    const d = date;
    const map = new Map();
    function full(num) {
        return num < 10? String( '0' + num): String(num);
    }
    Date.prototype.getRMonth = function(){return this.getMonth() + 1};
    Date.prototype.getRDay = function() {
        const map = ['日', '一', '二', '三', '四', '五', '六'];
        return map[this.getDay()];
    }
    Date.prototype.getSmYear = function(){return String(this.getYear()).substr(-2)};
    Date.prototype.getFullMonth = function() {return full(this.getRMonth())};
    Date.prototype.getFullDate = function() {return full(this.getDate())};
    Date.prototype.getAPHours = function(){return this.getHours() % 12};
    Date.prototype.getFullHours = function(){return full(this.getHours())};
    Date.prototype.getFullAPHours = function(){return full(this.getAPHours())};
    Date.prototype.getFullMin = function(){return full(this.getMinutes())};
    Date.prototype.getFullSec = function(){return full(this.getSeconds())};
    map.set('yyyy', 'getFullYear');
    map.set('yy', 'getSmYear');
    map.set('MM', 'getFullMonth');
    map.set('M', 'getRMonth');
    map.set('dd', 'getFullDate');
    map.set('d', 'getDate');
    map.set('HH', 'getFullHours');
    map.set('H', 'getHours');
    map.set('hh', 'getFullAPHours');
    map.set('h', 'getApHours');
    map.set('mm', 'getFullMin');
    map.set('m', 'getMinutes');
    map.set('ss', 'getFullSec');
    map.set('s', 'getSeconds');
    map.set('w', 'getRDay');
    return format.replace(/yyyy|yy|MM|M|dd|d|HH|H|hh|h|mm|m|ss|s|w/g, function(a) {
        return date[map.get(a)]();
    })
}
发表于 2021-10-12 12:18:10 回复(0)

function formatDate(newDate, str){

var year=newDate.getFullYear();
str=str.replace(/yyyy/,year);
var month=newDate.getMonth()+1;
month=month<10?'0'+month:month;
str=str.replace(/MM/,month);
var date=newDate.getDate();
date=date<10?'0'+date:date;
str=str.replace(/dd/,date);
var hour=newDate.getHours();
hour=hour<10?'0'+hour:hour;
str=str.replace(/HH/,hour);
var min=newDate.getMinutes();
min=min<10?'0'+min:min;
str=str.replace(/mm/,min);
var sec=newDate.getSeconds();
sec=sec<10?'0'+sec:sec;
str=str.replace(/ss/,sec);
var day=newDate.getDay();
var arr=['日','一','二','三','四','五','六'];
str=str.replace(/w/,arr[day]);
return str

}
不知道他到底有什么特殊的用例,就是不通过,但是编译器上自测是给定的用例是正确的,测了别的时间也是正确显示的,求指教

发表于 2021-09-22 09:02:57 回复(0)
// 为什么不通过😣
function formatDate(timestamp, str) {
    let date = timestamp instanceof Date ? timestamp : new Date(timestamp);
    let addZero = function (num) {
        return String.prototype.padStart.call(num, 2, "0");
    };
    let week = ["日", "一", "二", "三", "四", "五", "六"];
    let match = {
        yyyy: date.getFullYear(),
        yy: String.prototype.substring.call(date.getFullYear(), 2),
        MM: addZero(date.getMonth() + 1),
        M: date.getMonth() + 1,
        dd: addZero(date.getDate()),
        d: date.getDate(),
        HH: addZero(date.getHours()),
        H: date.getHours(),
        hh: addZero(date.getHours() % 12),
        h: date.getHours() % 12,
        mm: addZero(date.getMinutes()),
        m: date.getMinutes(),
        ss: addZero(date.getSeconds()),
        s: date.getSeconds(),
        w: week[date.getDay()],
    };
    for (const key in match) {
        let item = match[key];
        str = str.replace(key, item);
    }
    return str;
}


发表于 2021-09-15 09:39:56 回复(0)
const fix = n => {
    return n > 9 ? n : '0' + n;
}

function formatDate(date, format) {
    let [year, month, day, hour, minute, second, weekday] = [
        date.getFullYear(),
        date.getMonth() + 1,
        date.getDate(),
        date.getHours(),
        date.getMinutes(),
        date.getSeconds(),
        date.getDay()
    ]
    format = format.replace('yyyy', year)
        .replace('yy', year - 2000)
        .replace('MM', fix(month))
        .replace('M', month)
        .replace('dd', fix(day))
        .replace('d', day)
        .replace('HH', fix(hour))
        .replace('H', hour)
        .replace('hh', fix(hour))
        .replace('h', hour)
        .replace('mm', fix(minute))
        .replace('m', minute)
        .replace('ss', fix(second))
        .replace('s', second)
        .replace('星期w', '星期' + ['日', '一', '二', '三', '四', '五', '六'][weekday])
    return format
}


发表于 2021-09-09 15:13:51 回复(0)
function formatDate(date, formatStr) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var week = getWeek(date.getDay())
  var hours = date.getHours()
  var hour12 = resolveHour12(date.getHours())
  var minutes = date.getMinutes()
  var seconds = date.getSeconds()
  return formatStr
    .replace(/y+/g, cb(year))
    .replace(/M+/g, cb(month))
    .replace(/d+/g, cb(day))
    .replace(/H+/g, cb(hours))
    .replace(/h+/g, cb(hour12))
    .replace(/m+/g, cb(minutes))
    .replace(/s+/g, cb(seconds))
    .replace(/w/g, week)
}

function cb(target) {
  return (s) => {
    var isYear = /y+/.test(s)
    // 除年份外,如果匹配的是两位,则都需要补满两位
    if (!isYear && s.length === 2) {
      return fill(target)
    }
    // 年份需要截取,其它返回原始字符串
    return isYear ? String(target).slice(-s.length) : target
  }
}

function resolveHour12(hours) {
  return hours > 12 ? hours % 12 : hours
}

function fill(value) {
  return value < 10 ? `0${value}` : value
}

function getWeek(value) {
  var map = ['日', '一', '二', '三', '四', '五', '六']
  return map[value]
}

发表于 2021-08-28 14:40:24 回复(0)
function formatDate(date, format) {
  const getYear = date.getFullYear() // 年
  const getMonth = date.getMonth() + 1 // 月
  const getDate = date.getDate() // 日
  const getHour = date.getHours() // 时
  const getMinutes = date.getMinutes() // 分
  const getSeconds = date.getSeconds() // 秒
  const getDay = date.getDay() // 周几

  const getHalfHours = getHour <= 12 ? getHour : Math.abs(12 - getHour)

  const formatMap = {
    yyyy: getYear,
    yy: getYear % 100,
    MM: getMonth < 10 ? '0' + getMonth : getMonth,
    M: getMonth,
    dd: getDate < 10 ? '0' + getDate : getDate,
    d: getDate,
    HH: getHour < 10 ? '0' + getHour : getHour,
    H: getHour,
    hh: getHalfHours < 10 ? '0' + getHalfHours : getHalfHours,
    h: getHalfHours,
    mm: getMinutes < 10 ? '0' + getMinutes : getMinutes,
    m: getMinutes,
    ss: getSeconds < 10 ? '0' + getSeconds : getSeconds,
    s: getSeconds,
    w: ['日', '一', '二', '三', '四', '五', '六'][getDay]
  }

  // 替换 字符串即可
  for (let key in formatMap) {
    format = format.replace(key, formatMap[key])
  }

  return format
}

发表于 2021-08-15 10:06:40 回复(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(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)

问题信息

难度:
17条回答 16034浏览

热门推荐

通过挑战的用户

查看代码