I have an javascript object with Date property which is being converted to JSON using JSON.stringify
I am on GMT+4 time zone (Russia/Moscow)
For example,
5 Jan 2012 converts to 2012-01-04T20:00:00.000Z
5 Jan 1975 converts to 1975-01-04T20:00:00.000Z
But in 1975 it was GMT+3 time zone, as daylight saving was canceled in Russia in 2011. So when it cames to server (java) it deserializes as:
2012-01-04T20:00:00.000Z becames 5 Jan 2012 00:00 – OK
1975-01-04T20:00:00.000Z becames 4 Jan 1975 23:00 – WRONG!
What is the recommended way to convert Date object to JSON in Javascript?
I would suggest passing the date/times around using their seconds since epoch notation, more specifically the number of seconds since the Unix Epoch (1 Jan 1970 00:00 GMT). If you’re not familiar with this, there is an example converter here: http://www.epochconverter.com/
This has a few advantages:
java.util.Date, see (getTime()too). (Note that this uses milliseconds.)new Date(1000 * 1326894706)). (Note that this uses milliseconds.)"yyyy-MM-dd HH:mm:ss".{ "datetime": 1326894706, "tz": "GMT" }is still shorter than{ "datetime": "18 Jan 2012 13:51:46 GMT" }.Considering it’s easy to get
Dateinstances from this in Java and JavaScript, you can then use aDateFormatterto convert it to/from text in Java. For JavaScript, using a library such as Date Format will help you render it as appropriate on the page (for example with something likenew Date(val * 1000).format("yyyy-mm-dd HH:MM")).