26 lines
1.0 KiB
Plaintext
26 lines
1.0 KiB
Plaintext
type DateFormat = 'YYYY-MM-DD' | 'MM/DD/YYYY' | 'DD-MMM-YYYY' | 'YYYY年MM月DD日' | 'YYYYMMDD';
|
|
|
|
export function formatDate(date: Date,pattern:DateFormat = 'YYYY-MM-DD'): string {
|
|
const padZero = (num: number): string => num.toString().padStart(2, '0');
|
|
const year = date.getFullYear();
|
|
const month = padZero(date.getMonth() + 1); // 月份修正[7,8](@ref)
|
|
const day = padZero(date.getDate());
|
|
|
|
// 模式映射逻辑(核心补全部分)
|
|
switch (pattern) {
|
|
case 'YYYY-MM-DD':
|
|
return `${year}-${month}-${day}`;
|
|
case 'MM/DD/YYYY':
|
|
return `${month}/${day}/${year}`;
|
|
case 'DD-MMM-YYYY':
|
|
const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
|
|
return `${day}-${months[date.getMonth()]}-${year}`; // 月份缩写处理[4](@ref)
|
|
case 'YYYY年MM月DD日':
|
|
return `${year}年${month}月${day}日`; // 中文格式[5](@ref)
|
|
case 'YYYYMMDD':
|
|
return `${year}${month}${day}`; // 紧凑格式
|
|
default:
|
|
throw new Error(`Unsupported format pattern: ${pattern}`);
|
|
}
|
|
}
|