42 lines
1.2 KiB
JavaScript
42 lines
1.2 KiB
JavaScript
/**
|
||
* 日期格式化
|
||
* @param {Date|number|string} time 时间戳/日期字符串/Date对象
|
||
* @param {string} fmt 格式 'yyyy-MM-dd HH:mm:ss'
|
||
* @returns {string}
|
||
*/
|
||
export function formatDate(time, fmt = 'yyyy-MM-dd HH:mm:ss') {
|
||
if (!time) return ''
|
||
let date
|
||
if (typeof time === 'number') {
|
||
// 小程序时间戳注意:毫秒直接用,秒要*1000
|
||
date = new Date(time.toString().length === 10 ? time * 1000 : time)
|
||
} else {
|
||
date = new Date(time)
|
||
}
|
||
// 兼容ios:2025-08-01 → 2025/08/01
|
||
if (isNaN(date.getTime())) {
|
||
date = new Date(String(time).replace(/-/g, '/'))
|
||
}
|
||
if (isNaN(date.getTime())) return ''
|
||
|
||
const o = {
|
||
'M+': date.getMonth() + 1, // 月
|
||
'd+': date.getDate(), // 日
|
||
'H+': date.getHours(), // 24小时制
|
||
'h+': date.getHours() % 12, //12小时
|
||
'm+': date.getMinutes(), // 分
|
||
's+': date.getSeconds(), // 秒
|
||
'q+': Math.floor((date.getMonth() + 3) / 3), //季度
|
||
'S': date.getMilliseconds() //毫秒
|
||
}
|
||
if (/(y+)/.test(fmt)) {
|
||
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
|
||
}
|
||
for (const k in o) {
|
||
if (new RegExp(`(${k})`).test(fmt)) {
|
||
const str = o[k] + ''
|
||
fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : str.padStart(2, '0'))
|
||
}
|
||
}
|
||
return fmt
|
||
} |