- 代码合并:通过formatType参数控制输出格式
- 参数复用:Date对象创建操作只执行一次,避免重复计算
- 可扩展性:新增格式类型只需添加case分支即可扩展
const formatDate = (date, formatType) => {
const dateObj = new Date(date);
const month = String(dateObj.getMonth() + 1).padStart(2, '0');
const day = String(dateObj.getDate()).padStart(2, '0');
const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][dateObj.getDay()];
switch (formatType) {
case 'day':
return `${month}-${day}`;
case 'week':
return week;
default:
return '';
}
};
进行调用
ormatDate(data, 'day') // 输出 "03-15"
formatDate(data, 'week') // 输出 "周一"