a7a0a54688
Co-authored-by: Cursor <cursoragent@cursor.com>
73 lines
2.2 KiB
TypeScript
73 lines
2.2 KiB
TypeScript
/**
|
|
* 微信小程序基础库无 Intl。业务代码已避免依赖,此处仅作兜底,
|
|
* 防止旧包 / 依赖偶发 `new Intl.DateTimeFormat` 直接白屏。
|
|
*/
|
|
function pad(n: number) {
|
|
return String(n).padStart(2, '0');
|
|
}
|
|
|
|
function shanghaiParts(date: Date) {
|
|
const sh = new Date(date.getTime() + 8 * 60 * 60 * 1000);
|
|
return {
|
|
year: String(sh.getUTCFullYear()),
|
|
month: pad(sh.getUTCMonth() + 1),
|
|
day: pad(sh.getUTCDate()),
|
|
hour: pad(sh.getUTCHours()),
|
|
minute: pad(sh.getUTCMinutes()),
|
|
second: pad(sh.getUTCSeconds()),
|
|
};
|
|
}
|
|
|
|
function installIntlStub() {
|
|
const root = (typeof globalThis !== 'undefined'
|
|
? globalThis
|
|
: typeof global !== 'undefined'
|
|
? global
|
|
: typeof wx !== 'undefined'
|
|
? wx
|
|
: {}) as typeof globalThis & { Intl?: typeof Intl };
|
|
|
|
if (typeof root.Intl !== 'undefined' && typeof root.Intl.DateTimeFormat === 'function') {
|
|
return;
|
|
}
|
|
|
|
class MiniDateTimeFormat {
|
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
constructor(_locales?: string | string[], _options?: Record<string, unknown>) {}
|
|
|
|
format(date?: Date | number) {
|
|
const d = date instanceof Date ? date : new Date(date ?? Date.now());
|
|
if (Number.isNaN(d.getTime())) return '';
|
|
const p = shanghaiParts(d);
|
|
return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}`;
|
|
}
|
|
|
|
formatToParts(date?: Date | number) {
|
|
const d = date instanceof Date ? date : new Date(date ?? Date.now());
|
|
if (Number.isNaN(d.getTime())) return [];
|
|
const p = shanghaiParts(d);
|
|
return [
|
|
{ type: 'year', value: p.year },
|
|
{ type: 'literal', value: '-' },
|
|
{ type: 'month', value: p.month },
|
|
{ type: 'literal', value: '-' },
|
|
{ type: 'day', value: p.day },
|
|
{ type: 'literal', value: ' ' },
|
|
{ type: 'hour', value: p.hour },
|
|
{ type: 'literal', value: ':' },
|
|
{ type: 'minute', value: p.minute },
|
|
{ type: 'literal', value: ':' },
|
|
{ type: 'second', value: p.second },
|
|
];
|
|
}
|
|
}
|
|
|
|
root.Intl = {
|
|
DateTimeFormat: MiniDateTimeFormat,
|
|
} as unknown as typeof Intl;
|
|
}
|
|
|
|
installIntlStub();
|
|
|
|
export {};
|