2

My graph (a complex JS library I'd prefer not to modify) requires Javascript timestamps that are in local time (the graph doesn't adjust for timezone and DST so it must be done on database side.) for drawing the time axis - the source data is pretty much untouchable.

I use the same data to display a tooltip, which is pretty much "cook my own", to display precise values of data points.

Now comes the problem:

  • If I use Date(x).toUTCString() I'm getting the correct value displayed according to international locales - English month and day name etc.
  • If I use Date(x).toLocaleString() I'm getting the correct formatting but the date displayed is off by my timezone+DST offset; it's been already added on the server side and now the function adds it again.

Date(x).toString and Date(x).toGMTString weren't helpful either.

How do I get locale-formatted date that is not timezone-adjusted?

4

1 回答 1

-1

The way to achieve this is to initialize the Date object to contain the right time in GMT as opposed to initializing it to local time which it then believes is GMT and re-adjusts during reinitialization. In order to do that we abuse the Date constructor syntax of Date(Year,Month,day,hour,minute,seconds,ms). This violates the standard but works in all major browsers:

      Date(0,0,0,0,0,0,x).toLocaleString();

This prints the correctly localized string, with x containing the local timestamp.

If your x is not the int containing the number of milliseconds, but a javascript Date object with the date wrong, use:

      Date(0,0,0,0,0,0,x.getTime()).toLocaleString();
于 2013-09-10T12:45:32.873 回答