consumer-app/utils/date.js

56 lines
1.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* 时间戳转换工具
*/
/**
* 格式化时间戳
* @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');
}