This commit is contained in:
张成
2025-11-09 18:05:03 +08:00
parent 712ebe6463
commit 0090fc45c6
9 changed files with 211 additions and 110 deletions

View File

@@ -1,5 +1,21 @@
import dayjs from "dayjs";
/**
* 安全地将字符串转换为 Date 对象,兼容 iOS
* iOS 不支持 "yyyy-MM-dd HH:mm:ss" 格式,需要转换为 "yyyy-MM-ddTHH:mm:ss" 或 "yyyy/MM/dd HH:mm:ss"
* @param dateStr 日期字符串
* @returns Date 对象
*/
const parseDate = (dateStr: string): Date => {
if (!dateStr) return new Date();
// 将 "yyyy-MM-dd HH:mm:ss" 格式转换为 "yyyy-MM-ddTHH:mm:ss" (ISO 8601)
// 替换第一个空格为 T
const isoStr = dateStr.replace(/^(\d{4}-\d{2}-\d{2})\s(\d{2}:\d{2}(?::\d{2})?)$/, '$1T$2');
return new Date(isoStr);
};
/**
* 获取下一个整点时间
* @returns 格式为 YYYY-MM-DD HH:mm 的字符串
@@ -88,7 +104,7 @@ export const getTime = (time: string): string => {
export const formatRelativeTime = (timeStr: string): string => {
if (!timeStr) return "";
const date = new Date(timeStr);
const date = parseDate(timeStr);
const now = new Date();
// 获取日期部分(年-月-日),忽略时间
@@ -150,7 +166,7 @@ export const formatRelativeTime = (timeStr: string): string => {
export const formatShortRelativeTime = (timeStr: string): string => {
if (!timeStr) return "";
const date = new Date(timeStr);
const date = parseDate(timeStr);
const now = new Date();
// 获取日期部分(年-月-日),忽略时间
@@ -204,7 +220,7 @@ export const formatShortRelativeTime = (timeStr: string): string => {
export const formatGameTime = (timeStr: string): string => {
if (!timeStr) return "";
const date = new Date(timeStr);
const date = parseDate(timeStr);
const now = new Date();
// 获取星期几
@@ -287,8 +303,8 @@ export const calculateDuration = (
): string => {
if (!startTime || !endTime) return "";
const start = new Date(startTime);
const end = new Date(endTime);
const start = parseDate(startTime);
const end = parseDate(endTime);
// 计算时间差(毫秒)
const diffMs = end.getTime() - start.getTime();