consumer-app/utils/date.js

56 lines
1.4 KiB
JavaScript
Raw Normal View History

2025-12-19 12:27:55 +00:00
/**
* 时间戳转换工具
*/
/**
* 格式化时间戳
* @param {Number|String} timestamp 时间戳秒或毫秒
* @param {String} format 格式化模板默认 'YYYY.MM.DD HH:mm'
* @returns {String} 格式化后的时间字符串
*/
export function formatTime(timestamp, format = 'YYYY.MM.DD HH:mm') {
if (!timestamp) {
return '';
}
// 将时间戳转换为数字
let ts = Number(timestamp);
// 判断是秒级还是毫秒级时间戳大于10位数是毫秒级
if (ts.toString().length === 10) {
ts = ts * 1000;
}
const date = new Date(ts);
// 检查日期是否有效
if (isNaN(date.getTime())) {
return '';
}
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return format
.replace('YYYY', year)
.replace('MM', month)
.replace('DD', day)
.replace('HH', hours)
.replace('mm', minutes)
.replace('ss', seconds);
}
/**
* 格式化时间戳为默认格式 YYYY.MM.DD HH:mm
* @param {Number|String} timestamp 时间戳
* @returns {String} 格式化后的时间字符串
*/
export function formatDateTime(timestamp) {
return formatTime(timestamp, 'YYYY.MM.DD HH:mm');
}