// 将目标时区的墙上时间逆推为真实 UTC 时间戳(自动处理任意时区的夏令时跳空与重叠)
function zonedTimestamp(y, month, day, h = 0, min = 0, s = 0, ms = 0) {
y = +y; month = +month; day = +day; h = +h;
min = +min; s = +s; ms = +ms;
const getters = {
getFullYear: p => p.year,
getMonth: p => p.month - 1,
getDate: p => p.day,
getDay: p => p.weekday,
getHours: p => p.hour,
getMinutes: p => p.minute,
getSeconds: p => p.second,
getMilliseconds: p => p.ms,
getTimezoneOffset: p => p.offset,
getYear: p => p.year - 1900
};
for (const [method, get] of Object.entries(getters)) {
dateProto[method] = maskFunction(function () {
const p = zoned(nativeGetTime.call(this));
return p ? get(p) : NaN;
}, method);
}
function dateString(d) {
const p = zoned(nativeGetTime.call(d));
if (!p) return 'Invalid Date';
return ${DAYS[p.weekday]} ${MONTHS[p.month - 1]} ${pad(p.day)} ${p.year};
}
function timeString(d) {
const ts = nativeGetTime.call(d);
const p = zoned(ts);
if (!p) return 'Invalid Date';
for (const method of setters) {
const original = dateProto[method];
dateProto[method] = maskFunction(function (...args) {
if (args.length === 0) return nativeSetTime.call(this, NaN);
const p = zoned(nativeGetTime.call(this));
if (!p && method !== 'setFullYear' && method !== 'setYear') {
return original.apply(this, args);
}
let [y, mo, day, h, min, s, ms] = p
? [p.year, p.month, p.day, p.hour, p.minute, p.second, p.ms]
: [1970, 1, 1, 0, 0, 0, 0];
switch (method) {
case 'setFullYear':
y = +args[0];
if (args.length > 1) mo = +args[1] + 1;
if (args.length > 2) day = +args[2];
break;
case 'setMonth':
mo = +args[0] + 1;
if (args.length > 1) day = +args[1];
break;
case 'setDate':
day = +args[0];
break;
case 'setHours':
h = +args[0];
if (args.length > 1) min = +args[1];
if (args.length > 2) s = +args[2];
if (args.length > 3) ms = +args[3];
break;
case 'setMinutes':
min = +args[0];
if (args.length > 1) s = +args[1];
if (args.length > 2) ms = +args[2];
break;
case 'setSeconds':
s = +args[0];
if (args.length > 1) ms = +args[1];
break;
case 'setMilliseconds':
ms = +args[0];
break;
case 'setYear':
y = +args[0];
if (y >= 0 && y <= 99) y = Math.trunc(y) + 1900;
break;
}
return nativeSetTime.call(this, zonedTimestamp(y, mo, day, h, min, s, ms));
}, method);
可以共享、可以push的免费邮箱,更可使用自定义域名,完美契合您的各项需求。
10 条回复
排序