简体   繁体   English

Javascript-覆盖新的Date()行为以抵消GMT

[英]Javascript - overriding new Date() behavior to offset GMT

I'm developing a website that uses Comet to transmit data back to web clients. 我正在开发一个使用Comet将数据传输回Web客户端的网站。 My application is very time sensitive, I have a graph displaying points added every second. 我的应用程序对时间非常敏感,我有一个图表显示每秒添加的点。

Since the web application is Comet driven there is no real need for the client to handle dates, it should only use the server timestamp to display information. 由于Web应用程序是由Comet驱动的,因此客户端实际上不需要处理日期,因此它仅应使用服务器时间戳来显示信息。 ie a plotted point on the graph should display in the tooltip the server timestamp, regardless of the user's timezone. 也就是说,无论用户所在的时区如何,图形上的绘制点都应在工具提示中显示服务器时间戳。

I think my best approach would be to retrieve the server's timestamp using REST. 我认为我最好的方法是使用REST检索服务器的时间戳。 Then measure the timezone offset between the server and client time, add/deduct the difference and use it as the client's timestamp for display purposes. 然后,测量服务器与客户端时间之间的时区偏移量,添加/减去时差并将其用作客户端的时间戳,以进行显示。

Is there a way to override the default behavior of new Date() to result in me having the server's timestamp as the local? 有没有一种方法可以覆盖new Date()的默认行为,以使我将服务器的时间戳作为本地时间戳?

Many thanks. 非常感谢。

I wrote the library TimeShift.js that allows overriding the Date constructor and setting the current time and time zone. 我编写了库TimeShift.js ,该库可以覆盖Date构造函数并设置当前时间和时区。 I wrote it for testing purposes, but it could be used for other uses as well. 我出于测试目的编写了它,但是它也可以用于其他用途。

Be sure to check the caveats of the current library. 确保检查当前库的警告。 It currently only supports a fixed offset to GMT, so DST changes are not supported. 目前,它仅支持GMT的固定偏移量,因此不支持DST更改。

just redefine it, it should work fine: 只是重新定义它,它应该可以正常工作:

if(Date) {
    try{
        Date = null;
        Date = function() {
            console.log("The more things change, the more they stay the same!");
        }
        Date();
    } catch(exeption) {
        console.log("Couldn't override Date object.");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM