背景:最近在写react-native项目,后端返回时间戳,但各个设计稿给的时间格式都不相同...
目的:仿照Angular的date过滤器将其时间戳根据传参格式返回。
结果:
方法一:
function _timeFormat(date, format) {
if (!date) return
function add0(m) {
return m < 10 ? '0' + m : m
}
function concat(array1, array2, index) {
return array1.concat([].slice.call(array2, index));
}
let DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
time = new Date(date),
text = ''
let DATE_FORMATS = {
yyyy: time.getFullYear(),
yy: (time.getFullYear() + '').slice(2, 4),
MM: time.getMonth() + 1,
dd: time.getDate(),
hh: time.getHours(),
mm: time.getMinutes(),
ss: time.getSeconds()
}
let parts = []
while (format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
parts.forEach(value => {
if (DATE_FORMATS.hasOwnProperty(value)) {
if (value === 'yyyy' || value === 'yy') { text += DATE_FORMATS[value] }
else { text += add0(DATE_FORMATS[value]) }
} else {
text += value
}
})
return text
}
方法二:
function _dateFormat(date, format) {
let oDate = new Date(date)
let hours = oDate.getHours()
let ttime = 'AM'
if (format.indexOf('t') > -1 && hours > 12) {
hours = hours - 12
ttime = 'PM'
}
let o = {
'M+': oDate.getMonth() + 1,
'd+': oDate.getDate(),
'h+': hours,
'm+': oDate.getMinutes(),
's+': oDate.getSeconds(),
'q+': Math.floor((oDate.getMonth() + 3) / 3),
'S': oDate.getMilliseconds(),
't+': ttime
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (oDate.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (var k in o) {
if (new RegExp('(' + k + ')').test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
}
}
return format
}
_dateFormat(1567648218736, 'yyyy/MM/dd hh:mm') // 2019/09/05 09:50
_dateFormat(1567648218736, 'yy/MM/dd hh:mm') // 19/09/05 09:50
_dateFormat(1567648218736, 'yyyy-MM-dd hh:mm') // 2019-09-05 09:50
_dateFormat(1567648218736, 'yy-MM-dd hh:mm') // 19-09-05 09:50
_dateFormat(1567648218736, 'MM/dd/yy hh:mm') // 09/05/19 09:50
_timeFormat(1567648218736, 'yyyy/MM/dd hh:mm') // 2019/09/05 09:50
_timeFormat(1567648218736, 'yy/MM/dd hh:mm') // 19/09/05 09:50
_timeFormat(1567648218736, 'yyyy-MM-dd hh:mm') // 2019-09-05 09:50
_timeFormat(1567648218736, 'yy-MM-dd hh:mm') // 19-09-05 09:50
_timeFormat(1567648218736, 'MM/dd/yy hh:mm') // 09/05/19 09:50