需求
很多时候我们都需要对时间进行格式化的处理,不同的模块可能需要不同的时间格式甚至是不同的时间长度。
我认为最合理的处理时间的方式是在存储的时候存储时间戳,这样方便今后转换为任何时间格式,然后我简单封装了一个时间格式的处理方法,支持我们获取任意长度,任意格式的时间
格式时间
- 年: YYYY
- 月: M/MM (双字符长度代表自动补0)
- 日: D/DD
- 时: h/hh
- 分: m/mm
- 秒: s/ss
- 季度: Q 我们可以采取任何时间场地或任何形式进行拼接,例如:YYYY-MM-DD hh-mm-ss或者YYYY年MM月,该方法会自动识别其中的时间字段进行替换,从而保留其他拼接字符,注意不要使用代表时间格式的字符进行接。
js
const formatDate = (
dateTemplate = "YYYY-MM-DD hh:mm:ss",
date = new Date()
) => {
try {
// 处理日期输入,转换为Date对象
let targetDate;
if (date instanceof Date) {
targetDate = date;
} else {
targetDate = new Date(date);
}
// 检查日期有效性
if (isNaN(targetDate.getTime())) {
throw new Error("您传入的不是有效的日期格式!");
}
// 提取日期组件
const year = targetDate.getFullYear();
const month = targetDate.getMonth() + 1;
const dateNum = targetDate.getDate();
const hours = targetDate.getHours();
const minutes = targetDate.getMinutes();
const seconds = targetDate.getSeconds();
const quarter = Math.floor(month / 3) + 1;
// 定义替换规则映射表
const replacements = {
YYYY: year,
MM: String(month).padStart(2, "0"),
M: month,
DD: String(dateNum).padStart(2, "0"),
D: dateNum,
hh: String(hours).padStart(2, "0"),
h: hours,
mm: String(minutes).padStart(2, "0"),
m: minutes,
ss: String(seconds).padStart(2, "0"),
s: seconds,
Q: quarter, // 新增季度支持
};
// 执行替换
return Object.entries(replacements).reduce((str, [key, value]) => {
return str.replace(new RegExp(key, "g"), value);
}, dateTemplate);
} catch (error) {
console.error("日期格式化错误:", error.message);
return null; // 明确返回null表示格式化失败
}
};