function dateTran(timestamp) {
let date;
// 情况1:如果是 null、undefined、空字符串等,返回空或提示
if (!timestamp && timestamp !== 0) {
return '';
}
// 情况2:如果是 Date 对象
if (timestamp instanceof Date) {
date = timestamp;
}
// 情况3:如果是数字(时间戳)
else if (typeof timestamp === 'number') {
// 判断是秒级(10位)还是毫秒级(13位)
if (timestamp.toString().length === 10) {
date = new Date(timestamp * 1000); // 秒 → 毫秒
} else {
date = new Date(timestamp); // 直接作为毫秒
}
}
// 情况4:如果是字符串
else if (typeof timestamp === 'string') {
if (isPureNumericString(timestamp)) { // 纯数字字符串,如"1752550673411"
const X = Number(timestamp)
if (timestamp.length === 10) {
date = new Date(X * 1000); // 秒 → 毫秒
} else {
date = new Date(X); // 直接作为毫秒
}
} else { // 普通字符串,如"2025-09-17"
// 尝试解析字符串
date = new Date(timestamp);
// 如果是无效日期(如 "abc"),尝试进一步处理
if (isNaN(date.getTime())) {
// 常见格式:YYYY-MM-DD, YYYY/MM/DD, MM-DD-YYYY 等
const parsed = parseDateString(timestamp);
if (parsed) {
date = parsed;
} else {
return 'Invalid Date';
}
}
}
}
// 其他类型不支持
else {
return 'Invalid Date';
}
// 验证 date 是否有效
if (isNaN(date.getTime())) {
return 'Invalid Date';
}
// 格式化输出
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
// 辅助函数:判断字符串是否为纯数字字符串
function isPureNumericString(str) {
return typeof str === 'string' && /^\d+$/.test(str);
}
// 辅助函数:解析常见字符串格式(可选增强)
function parseDateString(str) {
const formats = [
/^\d{4}-\d{1,2}-\d{1,2}$/, // YYYY-M-D or YYYY-MM-DD
/^\d{1,2}-\d{1,2}-\d{4}$/, // M-D-YYYY
/^\d{4}\/\d{1,2}\/\d{1,2}$/, // YYYY/MM/DD
];
for (const regex of formats) {
if (regex.test(str)) {
// 替换 - 为 / 避免 Safari 等浏览器解析问题
const fixedStr = str.replace(/-/g, '/');
const d = new Date(fixedStr);
if (!isNaN(d.getTime())) {
return d;
}
}
}
return null;
}
export { dateTran };
自适应时间戳转换
于 2025-09-02 16:06:27 首次发布
335

被折叠的 条评论
为什么被折叠?



