- TextPart: default import → named import - MaterialCard: 使用 formatDateLabel 显示今天/昨天/日期 - 清理旧测试文件,新增 ResourceTable 测试
64 lines
2.3 KiB
TypeScript
64 lines
2.3 KiB
TypeScript
export function formatCountdown(seconds: number): string {
|
|
if (seconds < 60) return `${seconds}秒`;
|
|
return `${Math.floor(seconds / 60)}分${seconds % 60}秒`;
|
|
}
|
|
|
|
export function formatDateLabel(dateStr: string, now: Date = new Date()): string {
|
|
const date = new Date(dateStr);
|
|
if (Number.isNaN(date.getTime())) return "—";
|
|
|
|
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
|
const yesterday = new Date(today.getTime() - 86_400_000);
|
|
const dateDay = new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
|
|
|
if (dateDay.getTime() >= today.getTime()) return "今天";
|
|
if (dateDay.getTime() >= yesterday.getTime()) return "昨天";
|
|
|
|
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}`;
|
|
}
|
|
|
|
export function formatDurationUnit(ms: null | number): { suffix: string; value: number } {
|
|
if (ms === null) return { suffix: "", value: 0 };
|
|
if (ms < 60000) return { suffix: "秒", value: roundToOne(ms / 1000) };
|
|
if (ms < 3600000) return { suffix: "分钟", value: roundToOne(ms / 60000) };
|
|
return { suffix: "小时", value: roundToOne(ms / 3600000) };
|
|
}
|
|
|
|
export function formatRelativeTime(timestamp: null | string, now = new Date()): string {
|
|
if (!timestamp) return "尚无检查数据";
|
|
|
|
const time = new Date(timestamp).getTime();
|
|
if (Number.isNaN(time)) return "尚无检查数据";
|
|
|
|
const diffSeconds = Math.max(0, Math.floor((now.getTime() - time) / 1000));
|
|
if (diffSeconds < 60) return `${diffSeconds}秒前`;
|
|
|
|
const diffMinutes = Math.floor(diffSeconds / 60);
|
|
if (diffMinutes < 60) return `${diffMinutes}分钟前`;
|
|
|
|
const diffHours = Math.floor(diffMinutes / 60);
|
|
if (diffHours < 24) return `${diffHours}小时前`;
|
|
|
|
return `${Math.floor(diffHours / 24)}天前`;
|
|
}
|
|
|
|
export function isOlderThan(timestamp: null | string, ageMs: number, now = new Date()): boolean {
|
|
if (!timestamp) return false;
|
|
const time = new Date(timestamp).getTime();
|
|
if (Number.isNaN(time)) return false;
|
|
return now.getTime() - time > ageMs;
|
|
}
|
|
|
|
export function subtractHours(date: Date, hours: number): Date {
|
|
const result = new Date(date);
|
|
result.setTime(result.getTime() - hours * 60 * 60 * 1000);
|
|
return result;
|
|
}
|
|
|
|
function roundToOne(value: number): number {
|
|
return Math.round(value * 10) / 10;
|
|
}
|