Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON dates without timezone

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?

like image 216
knepe Avatar asked Sep 23 '10 17:09

knepe


People also ask

How can I date without a time zone?

To create a date without timezone:Get the ISO representation of the date string. Remove the Z character from the end of the ISO string. Pass the result to the Date() constructor.

How do I set date format in JSON?

JSON does not have a built-in type for date/time values. The general consensus is to store the date/time value as a string in ISO 8601 format.

Does JSON Stringify convert date to UTC?

stringify converts DateTimeOffset to UTC format #1710.

Does JSON support date format?

JSON does not directly support the date format and it stores it as String. However, as you have learned by now that mongo shell is a JavaScript interpreter and so in order to represent dates in JavaScript, JSON uses a specific string format ISODate to encode dates as string.


1 Answers

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))
like image 61
bobince Avatar answered Sep 30 '22 10:09

bobince