Skip to content

Instantly share code, notes, and snippets.

@ClausClaus
Created January 28, 2019 02:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ClausClaus/413eb490956b5d3556386e537f23acc3 to your computer and use it in GitHub Desktop.
Save ClausClaus/413eb490956b5d3556386e537f23acc3 to your computer and use it in GitHub Desktop.
日期时间戳格式化
function formatDate(date, formatStr) {
if (/(Y+)/.test(formatStr)) {
formatStr = formatStr.replace(
RegExp.$1,
(date.getFullYear() + '').substr(4 - RegExp.$1.length)
)
// 返回年 :'2016-mm-dd', 'hh:mm'
}
// 定义通用的匹配模式
let o = {
'M+': date.getMonth() + 1,
'D+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
// RegExp.$1.length 代表的是MM、dd、ss 这些
for (var k in o) {
if (new RegExp(`(${k})`).test(formatStr)) {
let str = o[k] + ''
formatStr = formatStr.replace(
RegExp.$1,
RegExp.$1.length === 1 ? str : padLeftZero(str)
)
}
}
return formatStr // 2016-07-23
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment