Usha Guduri

Dates & Times - Front & Back

Not that I did not learn anything the past week but that so much has been happening that i failed to make time to write about it!

Now to the mystery behind dates transferred between the front end(client browser) getting changed when coming back from the backend (Java)…

If you think creating Date objects is so simple, behold! there is something called a “timezone” which gets used for generating the Dates - both by Javascript and Java. And it depends on where the machine is located - in some countries it also depends on what part of the year with the stupid and confusing “daylight savings time”.

In Javascript:

1
2
3
new Date();          // Creates a Date with the local time for the browser
new Date(milliseconds); // Gives a Date with the ms offset from 1/1/1970 UTC
new Date(text);      // Parses the text from standard formats with the local timezone unless, the timezone is included

Similarly in Java:

1
new Date(milliseconds); // Gives a Date with the ms offset from 1/1/1970 GMT which is affected by daylight savings

So even if you think passing milliseconds will do the job, you are mistaken because one is using UTC and the other GMT.

Solution: There are several approaches to solving this problem, that need to be carefully evaluated:

  1. Use UTC times as the protocol to interpret on both ends:
    • there’s a handy jvm option to ensure that all dates on the java side are interpreted as UTC: —Duser.timezone=UTC

    The problem however is that you will be swamped with UTC dates in the java land(logs, output etc) which is just too cumbersome when debugging a problem.

    • a better route to this approach: use UTC in code where needed and the rest of the jvm uses the default timezone of the machine, so other processes do not have to change.
  2. Pass timezones in the date string format, so the dates are created correctly
  3. Pass around the date/month/year as just that - 3 parameters and each end would know how to display/use them.

Lesson: Never send milliseconds since epoch back and forth, since they are interpreted differently based on where the machine is located!

Comments