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

时间格式化输出

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

function formatDate(date, format) {
  let formatArr = [];
  format.replace(/\w+|:|\s|-|星期/g, function (text) {
    text && formatArr.push(text)
  })
  const weekday = ['日', '一', '二', '三', '四', '五', '六'];
  const map = {
    'yyyy': date.getFullYear(),
    'yy': date.getFullYear() % 100,
    'MM': date.getMonth() + 1 >= 10 ? date.getMonth() + 1 : "0" + (date.getMonth() + 1),
    'M': date.getMonth() + 1,
    'dd': date.getDate() >= 10 ? date.getDate() : "0" + date.getDate(),
    'd': date.getDate(),
    'HH': date.getHours() >= 10 ? date.getHours() : "0" + date.getHours(),
    'H': date.getHours(),
    'hh': (date.getHours() % 12) >= 10 ? (date.getHours() % 12) : "0" + (date.getHours() % 12),
    'h': (date.getHours() % 12),
    'mm': date.getMinutes() >= 10 ? date.getMinutes() : "0" + date.getMinutes(),
    'm': date.getMinutes(),
    'ss': date.getSeconds() >= 10 ? date.getSeconds() : "0" + date.getSeconds(),
    's': date.getSeconds(),
    'w': weekday[date.getDay()]
  };

  return formatArr.map(item => {
    if (map[item]) {
      return map[item]
    }
    return item
  }).join("")
}

全部评论

相关推荐

雪飒:我也遇见过,我反问他有考虑来华为od吗?
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
03-28 13:48
hory权:校招vip纯神人了,还说自己是什么师范大学的
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务