前言
这两天写需求要用到时间,就想找一个JavaScript按照指定格式返回时间字符串的方法。
结果不是代码太长,就是难理解,要么就是使用的方法已废弃。
所以抽时间写了一个dateFormat
方法。
代码
const dateFormat = (
fmt,
date = new Date()
) => {
const formatDate = new Date(date);
const formatMap = {
Y: (len) => formatDate.getFullYear().toString().slice(-len),
M: (len) => (formatDate.getMonth() + 1).toString().padStart(len, '0'),
D: (len) => formatDate.getDate().toString().padStart(len, '0'),
H: (len) => formatDate.getHours().toString().padStart(len, '0'),
m: (len) => formatDate.getMinutes().toString().padStart(len, '0'),
s: (len) => formatDate.getSeconds().toString().padStart(len, '0'),
S: (len) => formatDate.getMilliseconds().toString().padStart(len, '0'),
};
return fmt.replace(new RegExp(`[${Object.keys(formatMap).join('')}]+`, 'g'), match => formatMap[match[0]](match.length));
};
运行结果如下:
dateFormat('yyyy/MM/dd h:m:s::S')
// '2024/07/17 11:15:5::129'
dateFormat('年份:yyyy;月份:M;日期:d;时间:hh:mm:ss::S')
// '年份:2024;月份:7;日期:17;时间:11:15:05::702'
扩展
那么假设我现在又想加一个星期,怎么办呢?
可以在formatMap
里增加一个d
属性代表星期:
d: (len) => formatDate.getDay().toString()
那我想要dd
返回周日
,ddd
返回星期天
呢?
d: (len) => len === 1 ? formatDate.getDay() : len === 2 ? `周${['日', '一', '二', '三', '四', '五', '六'][formatDate.getDay()]}` : `星期${['天', '一', '二', '三', '四', '五', '六'][formatDate.getDay()]}`
增加个季度呢?
q: (len) => Math.ceil((formatDate.getMonth() + 1) / 3).toString().padStart(len, '0')
此时再运行:
dateFormat('yyyy/MM/dd h:m:s::S 季度q d dd ddd')
// '2024/07/17 11:17:38::562 季度3 2 周三 星期三'