Search code examples
javatimezonejava.util.date

Java.util.date get the actual date at client timezone


Searching up and down, right and left - don't find simple answer to this question:

I have java.util.Date instance, which get its value from mySQL.

Also I have time-zone code of the logged-in user.

I need to get the actual time at user time-zone.

For example:

My server-machine time-zone is GMT+2.

My date value in DB is: 2017-02-09 16:38:58.000

According to my server-machine-time-zone I get it into date instance as: 2017-02-09T16:38:58.000+0200

Now I need to know what to do if:

In case, for sample, my client-time-zone-code is GMT+4, I want to get:

2017-02-09 20:38:58.000

Pure date, that is right to my time zone and not contain "+4" or "GMT" indication.

In short words: convert my java.util.date to pure date that right to specific time-zone.

Sound very simple? after read very much documentaion, I already not sure that this is really simple.


Solution

  • java.util.Date does not store any time zone. It just stores the number of milliseconds since the 'epoch', which is 1 January 1970, 00:00:00 UTC.

    Thus, all you have to do is to know the time zone of your server machine, find the period between this time zone and the time zone you want to convert it to and add or subtract the period.

    UPDATE:

    int clientGMT = 4; //GMT you want to convert to
    int serverGMT = 2; //server's GMT
    int delta = clientGMT - serverGMT; //delta between the dates
    
    //assume this is the date in GMT + 2 received from the server
    Date d1 = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss").parse("12.03.2019 13:00:00");
    
    //... and you want to convert it to GMT + 4 (client side's time zone)
    Date resultDate = new Date(d1.getTime() + delta * 3600000);
    

    P.S. Yes, you have to manipulate time zones manually, as I said above, java.util.Date does not store this information (each date is assumed to be in UTC).