1

I have HTML page were customers can enter the date and time in format MM/dd/yyyy HH:mm. The problem I’m having is that depending on the client timezone the time is different (and might be date as well) on server side.

We are using Java and we are parsing the date with a code like this:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
Date date = sdf.parse(dateStr);

How can I detect the timezone of the user and convert the date time to server-side timezone?

1 Answers1

3

The best thing you can do is parse it on client side and send to the server the number of millis since EPOCH:

var millis = new Date(dateStr).getTime();

When you get the millis on server side, you can just create a Date object like this:

Date date = new Date(millis);

This will give you the correct date and time.

My advice: always use millis since EPOCH to avoid issues with timezones. Only convert to string when you need to show it to the user.

dgaviola
  • 2,421
  • 2
  • 26
  • 37
  • Sorry, but this doesn't answer the question asked. Also, timestamps of this sort are UTC based. Sometimes that is desired, but sometimes it is not. For example, if the user and the server have different time zone settings, then assuming UTC may result in a different time than the user entered. – Matt Johnson-Pint Sep 25 '19 at 17:03
  • I think it does answer the question. When you convert to milliseconds since EPOCH, you are eliminating the timezone. So no matter what timezone the client side and server side are using, it will always be parsed correctly. – dgaviola Sep 25 '19 at 17:25
  • The question was specifically, how to determine the user's time zone. Not how to eliminate it. There are many reasons to know the user's time zone on the server side. In the case presented here, `"...customers can enter the date and time in format MM/dd/yyyy HH:mm..."`, the customer's are likely to be providing input in their own time zone. The milliseconds-since-epoch are then based on how that time zone relates to UTC. If the server-side code is using a different time zone, then it will produce a different value than the user originally provided. – Matt Johnson-Pint Sep 25 '19 at 19:00
  • As I mentioned in my answer, you should parse the date on client side. For that reason, you will get the correct time for the user. Then, you pass the milliseconds since EPOCH to server side. No matter what's the timezone on server side, when you parse it, it will be correct. If you format, then you will end up with a different time based on the timezone you use to format it, but the date-time is the same in client and server side. – dgaviola Sep 25 '19 at 19:54