js Date() 构造函数 问题

我想重写 Date类 的getTime() 和 valueof()方法,使得在不同时区,获取的时间戳都是东8区的时间戳。在prototype内部,因为getTime() 和 valueof()被重写,应该用什么方法来获取到Date的标准时间戳。

阅读 2.2k
1 个回答

如果要改写,可以这么改

Date.prototype.getTime = (() => {
    const getTime = Date.prototype.getTime;
    return function () {
        const time = getTime.bind(this)();
        return time + 8 * 3600 * 1000;
    };
})();

但是不建议你这么干,因为会影响其他使用 Date 对象的库。你可以扩展一个专门的函数,比如 getChineseTime()

推荐问题