简体   繁体   中英

Convert timestamp with specified offset for timezone with Date();

I've been digging through as many things as I can find, and I can't seem to find what it is I am looking for, so I am coming to the conclusion that I either don't know what I am looking for or its not possible. Either way..

What I am trying to achieve is taking a timestamp example: 1373439600000 and a given offset of -12 to 12 (is that correct, as far as range goes?) so I can then take that timestamp above subtract from it accordingly, and pass that new timestamp to the Date() function so I can then manipulate it for human readable display.

The offset is two part, It is user specified in one instance while in the other it is going to default to the local getTimezoneOffset() if not specified. So trying to figure out how to take that range and work with that. To do everything accordingly.

Ideas? Am I even approaching this in a correct manor?

The timestamps I am working with are already UTC, not sure of that makes a difference.

The JavaScript Date type has many problems, but one of its major quirks is that it only understands two time zones - UTC, or Local. It uses UTC internally and in certain properties and functions like .toUTCString() , but otherwise it uses the local time zone.

Many browsers will accept an offset when parsing a Date from a string, but that will just be used to set the UTC time. Anything on the way out will be converted back to the local time zone again.

Fortunately, there are some great libraries out there for working around these problems. Moment.js is perfectly suited for this. Here is an example of what you might be looking for:

moment(1373439600000).zone(8).format("YYYY-MM-DD HH:mm:ss Z")

//  output: "2013-07-09 23:00:00 -08:00"

Of course, you can format as needed, or pass in a more complex zone offset like "+05:30" . And if you need to use an actual IANA time zone, there is the moment-timezone companion project, which you could do something like this:

moment(1373439600000).tz('America/New_York').format("YYYY-MM-DD HH:mm:ss Z")

//  output: "2013-07-10 03:00:00 -04:00"

Unfortunately the Date object does not provide may facilities for working with timezones. If you have the offset though, you should be able to compute the offset in milliseconds. Then you can add (subtract?) that value to your timestamp and use it to construct the appropriate Date .

Does that help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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