Skip to content

时间字符串格式化

时间字符串格式化

"2018/04/20 17:50:23" => "04-30 17:50"

js
let str = "2018/04/20 17:50:23" // => "04-30 17:50"
let reg = /^([1-9]\d{3})[\/-](资源缺失:\d[1-9][\/-](资源缺失:[0-3]\d) ([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/
// reg.exec(str)
// ["2018/04/20 17:50:23", "2018", "04", "20", "17", "50", "23", index: 0, input: "2018/04/20 17:50:23", groups: undefined]
let [, , month, day, hours, minutes ] = reg.exec(str)
let ret = `${month}-${day} ${hours}:${minutes}`
js
let str = "2018/04/20 17:50:23" // => "04-30 17:50"
let arr = str.match(/\d+/g).map(item => Number(item) < 10 ? '0' + Number(item) : item)
// 指定最后想要的时间格式,基于这个数组中的内容,然后拼接好
let template = `{1}月{2}日 {3}时{4}分{5}秒`
template = template.replace(/\{(\d+)\}/g, (...args) => {
  let [, index] = args // index: 每一次正则匹配小分组捕获到的内容
  return arr[index]
})

时间字符串格式化 完整版

js
String.prototype._formatTime = function formatTime(template = '{0}年{1}月{2}日 {3}时{4}分{5}秒') {
  // this: 当前字符串
  let arr = this.match(/\d+/g).map(item => Number(item) < 10 ? '0' + Number(item) : item)
  return template.replace(/\{(\d+)\}/g, (...[, index]) => arr[index] || '00')
}

let str = "2018/04/20 17:50:23"
str._formatTime()

共 20 个模块,1301 篇 Markdown 文档。