同步插件源代码并补齐标准项目文件
This commit is contained in:
67
utils/datetime.ts
Normal file
67
utils/datetime.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* 服务端时间都是「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";
|
||||
}
|
||||
Reference in New Issue
Block a user