Geuis
Geuis

Reputation: 42277

What format is this timestamp, and how can I format it in its own time

I have a problem converting a timestamp in javascript.

I have this timestamp:

2011-10-26T12:00:00-04:00

I have been trying to format it to be readable. So far, it converts this using the local time of my system instead of the GMT offset in the timestamp. I know the timezone that this was created in is EST. I'm in PST, so the times are being offset by 3 hours.

Instead of this showing as:

Wednesday October 26, 2011 12:00 pm

It shows as:

Wednesday October 26, 2011 9:00 am

I have tried a few different solutions, but the latest one is found here: http://blog.stevenlevithan.com/archives/date-time-format

I am less concerned with the formatting part as I am with figuring out how to handle the GMT offsets. Would appreciate any help and insight anyone can provide.

Upvotes: 1

Views: 1674

Answers (2)

RobG
RobG

Reputation: 147413

Date objects are created in the local zone. If the date string was created in a different time zone, then you need to adjust the date object to allow for the difference.

The abbreviations PST and EST are ambiguous on the web, there is no standard for time zone abbreviations and some represent two or zones. You should express your zone only in terms of +/- UTC or GMT (which are the same thing, more or less).

You can get the local time zone offset using Date.prototype.getTimezoneOffset, which returns the offset in minutes that must be added to a local time to get UTC. Calculate the offset for where the time string was created and apply it to the created date object (simply add or subtract the difference in minutes as appropriate).

If your time zone is -3hrs, getTimezoneOffset will return +180 for a date object created in that zone. If the string is from a zone -4hrs, its offset is +240. So you can do:

var localDate = new Date('2011-10-26T12:00:00') // date from string;
var originOffset = 240;
var localOffset = localDate.getTimezoneOffset();
localDate.setMinutes( localDate.getMinutes() + originOffset - localOffset );

Adding the origin offset sets it to UTC, subracting the local offset sets it to local time.

It would be much easier if the time string that was sent by the server was in UTC, that way you just apply the local offset.

Edit

IE will not parse a time string with an offset, and Chrome thinks that the above time string is UTC and adjusts for local offset. So don't let Date parse the string, do it manually.

Upvotes: 3

kennebec
kennebec

Reputation: 104780

It doesn't matter what time zone you are- the time stamp will result in a different local time for every different time-zone, but they all will be correct, and anyone checking the UTC time of the date will get the same time-stamp:

new Date('2011-10-26T12:00:00-04:00').toUTCString()
returns

Wed, 26 Oct 2011 16:00:00 GMT

and getTime() anywhere returns the same milliseconds universal timestamp:1319644800000

Upvotes: 0

Related Questions