题解 | #时间格式化输出#

时间格式化输出

http://www.nowcoder.com/practice/a789783e7c984f10a0bf649f6d4e2d59

function formatDate(d, formatter = 'yyyy-MM-dd HH:mm:ss') {
  const matches = {
    'y+': d.getFullYear(),          // 年
    'M+': d.getMonth() + 1,         // 月
    'd+': d.getDate(),              // 日
    'H+': d.getHours(),             // 时 (24h制)
    'h+': d.getHours() % 12,        // 时 (12h制)
    'm+': d.getMinutes(),           // 分
    's+': d.getSeconds(),           // 秒
    'w': '日一二三四五六'[d.getDay()] // 周
  }
  for (let symbol in matches) {
    if (RegExp(`(${symbol})`).test(formatter)) {   // 拼接括号()用于创建捕获组
      const val = matches[symbol], len = RegExp.$1.length // RegExp.$1就是formatter中捕获到的yyyy MM dd
      let replace = len === 1 ? val : ('000' + val).slice(-len) // 补零
      formatter = formatter.replace(RegExp.$1, replace)
    }
  }
  return formatter;
}

// ==TEST==
let d1 = new Date();
console.log(formatDate(d1))
全部评论

相关推荐

notbeentak...:孩子,说实话,选择很重要,可能你换一个方向会好很多,但是现在时间不太够了,除非准备春招
点赞 评论 收藏
分享
11-04 19:05
已编辑
东莞城市学院 单片机
不知道怎么取名字_:你这个要实习两年?哪有这么久的,感觉就是即使你毕业了,但还按实习的话,是不是不用给你缴社保公积金啥的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务