export default class Time { /** 1 秒时间戳 */ public static S = 1E3; /** 1 分钟时间戳 */ public static M = Time.S * 60; /** 1 小时时间戳 */ public static H = Time.M * 60; /** 1 天时间戳 */ public static D = Time.H * 24; public static now(): number { return new Date().getTime(); } /** * Unix 时间戳转日期 * * @param unix 时间戳 */ public static toDate(unix?: number): string { if (!unix) return ""; const d = new Date(unix); return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d.getDate().toString().padStart(2, "0")}`; } /** * Unix 时间戳转时间 * * @param unix 时间戳 */ public static toTime(unix?: number): string { if (!unix) return ""; const d = new Date(unix); return `${d.getHours().toString().padStart(2, "0")}:${d.getMinutes().toString().padStart(2, "0")}`; } /** * Unix 时间戳转日期和时间 * * @param unix 时间戳 */ public static toDateTime(unix?: number): string { if (!unix) return ""; return `${this.toDate(unix)} ${this.toTime(unix)}`; } public static toPassedDate(unix?: number): string { return this.toPassedDateTime(unix, false); } public static toPassedDateTime(unix?: number, withDetailTime = true): string { if (!unix) { return ""; } const now = new Date().getTime(); const between = now - unix; if (Time.D * 4 <= between) { return withDetailTime ? this.toDateTime(unix) : this.toDate(unix); } else if (Time.D < between) { return `${Math.floor(between / Time.D)} 天前`; } else if (Time.H < between) { return `${Math.floor(between / Time.H)} 小时前`; } else if (Time.M < between) { return `${Math.floor(between / Time.M)} 分钟前`; } else { return "刚刚"; } } public static between(begin: Date, end?: Date) : any { if (!end) { end = new Date(); } const cs = 1000, cm = 6E4, ch = 36E5, cd = 864E5, cy = 31536E6; const l = end.getTime() - begin.getTime(); const y = Math.floor(l / cy), d = Math.floor((l / cd) - y * 365), h = Math.floor((l - (y * 365 + d) * cd) / ch), m = Math.floor((l - (y * 365 + d) * cd - h * ch) / cm), s = Math.floor((l - (y * 365 + d) * cd - h * ch - m * cm) / cs), ms = Math.floor(((l - (y * 365 + d) * cd - h * ch - m * cm) / cs - s) * cs); return { l, y, d, h, m, s, ms }; } public static toMediaTime(seconds: number): string { seconds = Math.floor(seconds); const hours = Math.floor(seconds / 3600); const minutes = Math.floor((seconds % 3600) / 60); const second = seconds % 60; if (0 < hours) { return `${hours}:${minutes.toString().padStart(2, "0")}:${second.toString().padStart(2, "0")}`; } return `${minutes.toString().padStart(2, "0")}:${second.toString().padStart(2, "0")}`; } }