Created
January 28, 2019 02:17
-
-
Save ClausClaus/413eb490956b5d3556386e537f23acc3 to your computer and use it in GitHub Desktop.
日期时间戳格式化
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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