Files
klp-mono/apps/l2/src/utils/date-utils.js
砂糖 3db2ccf591 init
2025-10-10 16:47:38 +08:00

60 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 日期格式化格式化工具
* @param {Date|String|Number} time - 时间对象、字符串或时间戳
* @param {String} format - 格式化字符串,例如:'{yyyy}-{mm}-{dd} {hh}:{ii}:{ss}' 或 '{yyyyyy}-{mm}-{dd}T{hh}:{ii}:{ss}'
* @returns {String} 格式化后的日期字符串
*/
export function parseTime(time, format = '{yyyy}-{mm}-{dd} {hh}:{ii}:{ss}') {
if (!time) return '';
// 处理时间戳如果是10位数字转为毫秒
if (typeof time === 'number') {
if (time.toString().length === 10) {
time = time * 1000;
}
time = new Date(time);
}
// 处理字符串格式时间(核心修复)
if (typeof time === 'string') {
// 1. 清除可能的重复时间部分(如 "2025-08-12T00:00:00 00:00:00" → "2025-08-12T00:00:00"
time = time.replace(/(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2})\s+.*/, '$1');
// 2. 兼容iOS的日期格式将-转为/T转为空格
time = new Date(time.replace(/-/g, '/').replace('T', ' '));
}
// 如果不是Date对象直接返回
if (!(time instanceof Date) || isNaN(time.getTime())) {
return '';
}
const formatObj = {
y: time.getFullYear(),
m: time.getMonth() + 1,
d: time.getDate(),
h: time.getHours(),
i: time.getMinutes(),
s: time.getSeconds(),
a: time.getDay()
};
return format.replace(/{([ymdhisa])+}/g, (result, key) => {
const value = formatObj[key];
// 不足两位补零
if (value.toString().length < 2) {
return '0' + value;
}
return value || 0;
});
}
/**
* 生成传给后端的标准日期格式带T分隔符
* @param {Date|String|Number} time - 时间对象、字符串或时间戳
* @returns {String} 格式化后的日期字符串,例如:'2025-08-12T00:00:00'
*/
export function formatTimeForBackend(time) {
// 先清理时间格式再用T分隔符格式化
return parseTime(time, '{yyyy}-{mm}-{dd}T{hh}:{ii}:{ss}');
}