js
/**
* 将各种时间格式转换为指定格式的日期字符串或时间戳
* @param {Date|number|string|undefined} time 输入的时间(Date对象、时间戳、日期字符串或分隔符)
* @param {string} [format='yyyy-MM-dd HH:mm:ss'] 目标日期格式、分隔符或特定字符串('timestamp' 或 'timestamp-seconds')
* @returns {string|number} 指定格式的日期字符串或时间戳
*/
export function formatDate(time, format = "yyyy-MM-dd HH:mm:ss") {
let date;
let separator;
// 检查是否只传入了分隔符
if (typeof time === 'string' && time.length === 1) {
date = new Date();
separator = time;
format = `yyyy${separator}MM${separator}dd HH:mm:ss`;
} else if (time === undefined && format.length === 1) {
date = new Date();
separator = format;
format = `yyyy${separator}MM${separator}dd HH:mm:ss`;
} else {
date = time instanceof Date ? time : new Date(time);
if (isNaN(date.getTime())) throw new Error("Invalid date");
}
// 处理特殊格式要求
if (format === 'timestamp') {
return date.getTime();
}
if (format === 'timestamp-seconds') {
return Math.floor(date.getTime() / 1000);
}
const pad = (num) => String(num).padStart(2, "0");
const formats = {
yyyy: date.getFullYear(),
MM: pad(date.getMonth() + 1),
dd: pad(date.getDate()),
HH: pad(date.getHours()),
mm: pad(date.getMinutes()),
ss: pad(date.getSeconds()),
};
return format.replace(/yyyy|MM|dd|HH|mm|ss/g, (match) => formats[match]);
}
ts
/**
* 将各种时间格式转换为指定格式的日期字符串或时间戳
* @param {Date | number | string | undefined} time 输入的时间(Date对象、时间戳、日期字符串或分隔符)
* @param {string} [format='yyyy-MM-dd HH:mm:ss'] 目标日期格式、分隔符或特定字符串('timestamp' 或 'timestamp-seconds')
* @returns {string | number} 指定格式的日期字符串或时间戳
*/
export function formatDate(time?: Date | number | string, format: string = "yyyy-MM-dd HH:mm:ss"): string | number {
let date: Date;
let separator: string;
// 检查是否只传入了分隔符
if (typeof time === 'string' && time.length === 1) {
date = new Date();
separator = time;
format = `yyyy${separator}MM${separator}dd HH:mm:ss`;
} else if (time === undefined && format.length === 1) {
date = new Date();
separator = format;
format = `yyyy${separator}MM${separator}dd HH:mm:ss`;
} else {
date = time instanceof Date ? time : new Date(time as string | number | Date);
if (isNaN(date.getTime())) throw new Error("Invalid date");
}
// 处理特殊格式要求
if (format === 'timestamp') {
return date.getTime();
}
if (format === 'timestamp-seconds') {
return Math.floor(date.getTime() / 1000);
}
const pad = (num: number): string => String(num).padStart(2, "0");
const formats: { [key: string]: string | number } = {
yyyy: date.getFullYear(),
MM: pad(date.getMonth() + 1),
dd: pad(date.getDate()),
HH: pad(date.getHours()),
mm: pad(date.getMinutes()),
ss: pad(date.getSeconds()),
};
return format.replace(/yyyy|MM|dd|HH|mm|ss/g, (match: string): string => formats[match].toString());
}
页面使用
// 示例1:使用当前日期和时间
console.log(formatDate(new Date()));
// 输出: '2023-05-20 15:30:45' (具体时间会根据运行时的当前时间而变)
// 示例2:使用毫秒级时间戳
console.log(formatDate(1621497600000, 'yyyy-MM-dd'));
// 输出: '2021-05-20'
// 示例3:使用秒级时间戳
console.log(formatDate(1621497600, 'MM/dd/yyyy HH:mm'));
// 输出: '05/20/2021 12:00'
// 示例4:使用日期字符串,并自定义输出格式
console.log(formatDate('2024-08-05 02:58:02', 'yyyy年MM月dd日 HH时mm分'));
// 输出: '2024年08月05日 02时58分'
// 示例1:使用当前日期和时间
console.log(formatDate(new Date()));
// 输出: '2023-05-20 15:30:45' (具体时间会根据运行时的当前时间而变)
// 示例2:使用毫秒级时间戳
console.log(formatDate(1621497600000, 'yyyy-MM-dd'));
// 输出: '2021-05-20'
// 示例3:使用秒级时间戳
console.log(formatDate(1621497600, 'MM/dd/yyyy HH:mm'));
// 输出: '05/20/2021 12:00'
// 示例4:使用日期字符串,并自定义输出格式
console.log(formatDate('2024-08-05 02:58:02', 'yyyy年MM月dd日 HH时mm分'));
// 输出: '2024年08月05日 02时58分'
// 示例5:只输出年月
console.log(formatDate('2024-08-05', 'yyyy-MM'));
// 输出: '2024-08'
// 示例6:处理不同的输入格式
console.log(formatDate('August 5, 2024', 'dd/MM/yyyy'));
// 输出: '05/08/2024'
// 示例7:使用不同的分隔符
console.log(formatDate(1621497600000, 'yyyy.MM.dd HH:mm:ss'));
// 输出: '2021.05.20 12:00:00'
formatDate("/") // 返回 "2023/05/15 14:30:45"
formatDate("-") // 返回 "2023-05-15 14:30:45"
console.log(formatDate(date, 'timestamp')); // 1684581000000 (毫秒级时间戳)
console.log(formatDate(date, 'timestamp-seconds')); // 1684581000 (秒级时间戳)
// 示例8:错误处理
try {
console.log(formatDate('Invalid Date'));
} catch (error) {
console.log('Error:', error.message);
}
// 输出: 'Error: Invalid date'
ps:在部分 iOS 下无法正常使用,iOS 只支持 “yyyy/MM/dd”、“yyyy/MM/dd HH:mm:ss”、“yyyy-MM-dd”、“yyyy-MM-ddTHH:mm:ss”、“yyyy-MM-ddTHH:mm:ss+HH:mm” 的格式
感谢你的阅读,如对你有帮助请收藏+关注!
只分享干货实战和精品,从不啰嗦!!!
如某处不对请留言评论,欢迎指正~
博主可收徒、常玩QQ飞车,可一起来玩玩鸭~