1

I'm now writing web application that needs to transfer Date between Java and JavaScript. Firstly, I used milliseconds to exchange Date, which is mentioned here: https://stackoverflow.com/a/1007854/4675827.

However, there is a problem when it came across the DST, named Daylight Saving Time. The millisecond value for Java and JavaScript is different sometimes. Especially when I only store the date part of Date, I saved the time as: "2015-10-15 00:00:00", but when I pass the millisecond value to JavaScripts, it became "2015-10-14 23:00:00". Thus, the date part has 1-day difference.

I'm wondering what's the best practice to exchange Date data between Java and JavaScript, or can I turn off DST in Java?

Thanks in advance!


Finally, I was able to disable DST by changing timezone settings of Jackson mapper, which is used to serialize and deserialize json objects.

I changed to GMT+8, Beijing Time. It doesn't use DST at all.

mapper.setTimeZone(TimeZone.getTimeZone(ZoneId.of("GMT+8")));
Community
  • 1
  • 1
Fify
  • 131
  • 1
  • 8
  • 2
    Best practice is not to use client-side dates at all to store in DB – Tushar Oct 15 '15 at 04:24
  • if you do `var d = new Date(Date.parse(2015-10-15 00:00:00));` then the time stays correct but still dates from JS should not go to DB – Saar Oct 15 '15 at 04:28
  • @Saar—the use of *Date.parse* is redundant as strings passed to the Date constructor are parsed anyway. However, using built–in methods to parse date strings is not recommended. Also, your suggested format is not consistent with the ISO 8601 format specified in ECMA-262 ed 5 and 6 so results are implementation dependent. – RobG Oct 15 '15 at 04:31

1 Answers1

0

You don't provide any criteria for "best practice", however a robust way to transfer dates and times is using a time value. UNIX uses seconds since 1970-01-01T00:00:00Z and ECMAScript uses milliseconds since the same epoch, so conversion is simple.

If you always send a time value in seconds or milliseconds, then convert it to a Date on the client system (converting the time value to milliseconds if required), you will always get an equivalent Date object that can be used to display a date and time in either UTC or the client system timezone (often mistaken for "locale") which will automatically allow for daylight saving if in force.

There are many questions on that with good answers, e.g. Convert a Unix timestamp to time in JavaScript

Regarding date strings formatted per ISO 8601 like 2015-10-15T12:03:16Z, some browsers do not have built–in support for parsing such strings. If you provide a parser (say write your own or use a small library) then they can be reliably accommodated.

ISO 8601 strings can be handy as they are much more human comprehensible than time values, but that isn't a consideration if humans aren't expected to comprehend the data.

Community
  • 1
  • 1
RobG
  • 142,382
  • 31
  • 172
  • 209