0

Running into a JavaScript date weirdness that I cannot wrap my head around.

I have a date/time returned via WebAPI: '2012-12-13T12:17:06.080'. It's in local time (-7 UTC).

When running this date through JavaScript

var d = new Date('2012-12-14T05:32:05.543');
alert(d.toTimeString());

returns 22:32:05 MST

Then doing

var d = new Date('2012-12-14T05:32:05.543');
alert(d.toLocaleTimeString());

returns 10:32:05 PM

toTimeString/toLocaleTimeString() per JavaScript docs says it should just extract the Time portion, so why did the time change? What should I do to get it to return the correct time portion 05:32:05 without creating an supposedly unneeded function?

2
  • Is'nt it obvious? How should new Date know that you already subtracted the seven hours to get local time. It does'nt, so it treats all timestrings the same, and converts them to local time, subracting another seven hours, giving you the wrong time. Commented Dec 14, 2012 at 17:42
  • Yes, it's VERY obvious, but @Pointy made the point (ahem) that there's assumptions involved. Commented Dec 14, 2012 at 18:23

2 Answers 2

1

When you give the Date() constructor an ISO8601 timestamp string, it always interprets it as UTC.

Not all browsers behave the same way, and some don't like those at all.

Sign up to request clarification or add additional context in comments.

Comments

1

Here is a way to solve your problem:

Take the parts of the date and construct the date object manually.

I have attached a JSBin showcasing that http://jsbin.com/iduzaz/3/watch

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.