開源項目連接地址javascript
function formatType(type, format, value, regExpAttributes) {
const regExpMap = {
year: '(Y+)',
month: '(M+)',
date: '(D+)',
hour: '(h+)',
minute: '(m+)',
second: '(s+)',
quarter: '(q+)',
millisecond: '(S)'
}
if (new RegExp(regExpMap[type], regExpAttributes).test(format)) {
const replaceStr = type === 'year'
? value.toString().substr(4 - RegExp.$1.length)
: (RegExp.$1.length === 1) ? value : pad(value)
format = format.replace(RegExp.$1, replaceStr)
}
return format
}
function pad(value) {
return ('00' + value).substr(('' + value).length)
}
function formatDate(date, format) {
const map = {
year: {
value: date.getFullYear(),
regExpAttributes: 'i'
},
month: {
value: date.getMonth() + 1
},
date: {
value: date.getDate(),
regExpAttributes: 'i'
},
hour: {
value: date.getHours(),
regExpAttributes: 'i'
},
minute: {
value: date.getMinutes()
},
second: {
value: date.getSeconds()
},
quarter: {
value: Math.floor((date.getMonth() + 3) / 3),
regExpAttributes: 'i'
},
millisecond: {
value: date.getMilliseconds()
}
}
for (const key in map) {
format = formatType(key, format, map[key].value, map[key].regExpAttributes)
}
return format
}
複製代碼
console.log(
'result:',
formatDate(new Date(), 'YYYY.MM.DD hh:mm')
)
複製代碼
根據傳入日期對象參數,得到對應的月份7
, 根據匹配規則YYYY.MM.DD hh:mm
, 經過正則(M+)
找出MM
, 接着把7
替換MM
, 同時使用pad
函數處理下7
=> 07
, 24
=> 24
狀況,以此類推。java
pad
function pad(value) {
return ('00' + value).substr(('' + value).length)
}
複製代碼
若是值1
位數7
, 前面加00
, 即007
, 剪掉0
, 即07
git
若是值2
位數24
, 前面加00
, 即0024
, 剪掉00
, 即24
github
共同點,剪掉的是值的長度。bash
數字 + 字符串,必定是字符串相加,不是數字的累加,這點要注意。函數