Files
obsidian-rss-union/utils/datetime.ts

68 lines
2.2 KiB
TypeScript
Raw Permalink 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.
/**
* 服务端时间都是「YYYY-MM-DD HH:mm:ss」的本地时间字符串,
* 直接 new Date() 在部分环境会被当成 UTC,这里手动拆字段,避免差 8 小时。
*/
export function parseServerDate(raw: string): Date | null {
const text = String(raw || "").trim();
const m = text.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?/);
if (!m) return null;
return new Date(
Number(m[1]),
Number(m[2]) - 1,
Number(m[3]),
Number(m[4] || 0),
Number(m[5] || 0),
Number(m[6] || 0)
);
}
function pad(n: number): string {
return n < 10 ? `0${n}` : String(n);
}
/** 列表里显示的时间:今天 / 昨天 / N 天前,超过一周显示日期 */
export function formatListDate(raw: string): string {
const date = parseServerDate(raw);
if (!date) return String(raw || "").slice(0, 10);
const now = new Date();
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
const time = date.getTime();
const diffDays = Math.floor((startOfToday - new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()) / 86400000);
if (diffDays === 0) return `今天 ${pad(date.getHours())}:${pad(date.getMinutes())}`;
if (diffDays === 1) return `昨天 ${pad(date.getHours())}:${pad(date.getMinutes())}`;
if (diffDays > 1 && diffDays < 7) return `${diffDays} 天前`;
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}
/** 完整时间:阅读窗口头部用 */
export function formatFullDate(raw: string): string {
const date = parseServerDate(raw);
if (!date) return String(raw || "");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
/** 文件名 / 笔记标题用的日期前缀 */
export function dayStamp(raw?: string): string {
const date = parseServerDate(raw || "") || new Date();
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}
/** 文件名里不能出现的字符统一换掉 */
export function safeFileName(name: string, maxLength = 80): string {
const cleaned = String(name || "")
.replace(/[\\/:*?"<>|#^[\]]/g, " ")
.replace(/\s+/g, " ")
.trim();
return cleaned.slice(0, maxLength) || "untitled";
}