4

I have a webservice that returns for example a DateTime object: DepartureDate. I use ajax to fetch this and in my view I convert the JSON date string to a javascript date object with this function:

function convertToDate(jsonDate) {
    return eval("new " + jsonDate.substring(1, jsonDate.length - 1));
}

The problem is that new Date() takes the local time on the clients computer in consideration, so clients in different countries get different dates. I want to get the exact date that was returned from the webservice. Is there any easy way to accomplish this?

2
  • what the value of the variable "jsonDate" Commented Sep 23, 2010 at 17:54
  • could be for example "/Date(1285321800000)/" Commented Sep 23, 2010 at 18:01

1 Answer 1

6

The problem is that new Date() takes the local time on the clients computer in consideration

Nope. Creating a new Date using the timestamp constructor takes a UTC time stamp.

For example on my machine in UTC+1:

new Date(0)   // Thu Jan 01 1970 01:00:00 GMT+0100 (CET)

OK, the default toString displays this date as 01:00:00 which looks wrong, but that's actually the correct time. 01:00:00 in UTC+1 is 00:00:00 in UTC, which is the moment described by timestamp 0.

If you want to display the dates you've creating from a timestamp in UTC, use date.toUTCString() or fetch and format the consistuent parts of the date using getUTCFullYear(), getUTCMonth() etc.

Please, though, no eval.

new Date(parseInt(jsonDate.slice(6, -1), 10))
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your great answer bobince. I'm not good at dates and stuff, so I might not understand everything here, but I did what you suggested, and it's still the same result. If I change my timezone on my machine, the time changes (I want them to stay the same no matter what timezone your in, and they should follow AST timezone.)
The time displayed by toString() changes to reflect your time zone, but that does not mean the date is any different. new Date(1285321800000).getUTCHours() is always 9 regardless of your timezone. Stick with the getUTC... and setUTC... functions and the date will behave as you expect.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.