dayjs timezone插件中代码
proto.tz = function (timezone = defaultTimezone, keepLocalTime) {
const oldOffset = this.utcOffset(); const date = this.toDate();
const target = date.toLocaleString("en-US", { timeZone: timezone });
const diff = Math.round((date - new Date(target)) / 1000 / 60);
let ins = d(target)
.$set(MS, this.$ms)
.utcOffset(-Math.round(date.getTimezoneOffset() / 15) * 15 - diff, true);
if (keepLocalTime) {
const newOffset = ins.utcOffset();
ins = ins.add(oldOffset - newOffset, MIN);
}
ins.$x.$timezone = timezone; return ins;
};
date.toLocaleString 得到的target含有中文的字符串,然后丢给了dayjs(target)解析出现错误
总结:dayjs解析到了中文导致 Invalid Date
我的解决是改用了momentjs实现国际化转换 还有一种方案是重新实现一个dayjstimezone的插件在中间使用正则替换一下中文字符