Files
dyf-vue-ui/src/utils/common.ts

77 lines
2.3 KiB
TypeScript
Raw Normal View History

2025-09-03 14:16:47 +08:00
function DateFormat(date, format) {
if (!date) {
2025-09-09 16:34:54 +08:00
return '';
2025-09-03 14:16:47 +08:00
}
if (!format) {
format = 'yyyy-MM-dd HH:mm:ss';
}
// 处理参数默认值
if (typeof date === 'string' || typeof date === 'number') {
date = new Date(date);
}
date = date instanceof Date ? date : new Date();
format = format || 'yyyy-MM-dd';
// 检查日期是否有效
if (isNaN(date.getTime())) {
return 'Invalid Date';
}
// 定义格式化映射
const formatMap = {
'yyyy': date.getFullYear(),
'MM': String(date.getMonth() + 1).padStart(2, '0'),
'dd': String(date.getDate()).padStart(2, '0'),
'HH': String(date.getHours()).padStart(2, '0'),
'mm': String(date.getMinutes()).padStart(2, '0'),
'ss': String(date.getSeconds()).padStart(2, '0'),
'SSS': String(date.getMilliseconds()).padStart(3, '0'),
'M': date.getMonth() + 1,
'd': date.getDate(),
'H': date.getHours(),
'm': date.getMinutes(),
's': date.getSeconds(),
'S': date.getMilliseconds()
};
// 替换格式字符串中的占位符
return format.replace(/(yyyy|MM|dd|HH|mm|ss|SSS|M|d|H|m|s|S)/g, (match) => {
return formatMap[match];
});
}
2025-09-09 16:34:54 +08:00
function DateAdd(datePart, number, date) {
// 创建日期的副本,避免修改原日期对象
const newDate = new Date(date.getTime());
// 根据不同的时间单位添加相应的值
switch (datePart.toLowerCase()) {
case 'year':
newDate.setFullYear(newDate.getFullYear() + number);
break;
case 'month':
newDate.setMonth(newDate.getMonth() + number);
break;
case 'day':
newDate.setDate(newDate.getDate() + number);
break;
case 'hour':
newDate.setHours(newDate.getHours() + number);
break;
case 'minute':
newDate.setMinutes(newDate.getMinutes() + number);
break;
case 'second':
newDate.setSeconds(newDate.getSeconds() + number);
break;
default:
throw new Error('不支持的datePart参数。支持的参数: Year, Month, Day, Hour, Minute, Second');
}
return newDate;
}
2025-09-03 14:16:47 +08:00
export default{
2025-09-09 16:34:54 +08:00
DateFormat:DateFormat,
DateAdd:DateAdd
2025-09-03 14:16:47 +08:00
}