42 lines
1.3 KiB
TypeScript
42 lines
1.3 KiB
TypeScript
/**
|
||
* 时间格式化
|
||
*
|
||
* 以前属性里写的是 `new Date().toISOString()`,也就是
|
||
* `2026-11-11T06:09:43.465Z` 这种 UTC 串:中国香港 / 北京都在东八区,
|
||
* 本地时间其实是 14:09,看属性面板会以为时间差了 8 小时。
|
||
*
|
||
* 这里固定按 UTC+8 换算,不依赖本机时区——换一台时区不同的电脑、
|
||
* 或者在服务器上跑,输出都还是北京时间。
|
||
*/
|
||
const BEIJING_OFFSET_MS = 8 * 60 * 60 * 1000;
|
||
|
||
/**
|
||
* 把时间转成北京时间的 `YYYY-MM-DD HH:mm:ss`
|
||
*
|
||
* @param input Date / 时间戳 / 可解析的时间字符串,默认当前时刻
|
||
*/
|
||
export function formatBeijingTime(
|
||
input: Date | number | string = new Date()
|
||
): string {
|
||
const date = input instanceof Date ? input : new Date(input);
|
||
if (Number.isNaN(date.getTime())) return "";
|
||
|
||
// 先整体加 8 小时,再用 getUTC* 取值,得到的偏移量只由常量决定
|
||
const shifted = new Date(date.getTime() + BEIJING_OFFSET_MS);
|
||
const pad = (value: number) => String(value).padStart(2, "0");
|
||
|
||
const ymd = [
|
||
shifted.getUTCFullYear(),
|
||
pad(shifted.getUTCMonth() + 1),
|
||
pad(shifted.getUTCDate()),
|
||
].join("-");
|
||
|
||
const hms = [
|
||
pad(shifted.getUTCHours()),
|
||
pad(shifted.getUTCMinutes()),
|
||
pad(shifted.getUTCSeconds()),
|
||
].join(":");
|
||
|
||
return `${ymd} ${hms}`;
|
||
}
|