This seems like a stupid question, but I am not able to understand this creepy behavior. I am completely aware of the fact that java Date
class does not store any TimeZone information in it. It just stores the number of milliseconds since January 1, 1970, 00:00:00 GMT
Thing is that, I am using MySql which is residing on a server with UTC timezone and I am also storing DateTime
in UTC only. If I make a select query then I get this date 2014-01-17 16:15:49
By using http://www.epochconverter.com/ I get this:
Epoch timestamp: 1389975349
Timestamp in milliseconds: 1389975349000
Human time (GMT): Fri, 17 Jan 2014 16:15:49 GMT
Human time (your time zone): Friday, January 17, 2014 9:45:49 PM
Now comes the part of Hibernate. I am running my Java web app on a machine having IST as system timezone. I made a simple object fetch using Id and fetched createdDate
property which is a Date
object. I have wrote a simple code to understand its output, here is the code:
Date dt = c.getCreatedDate();
System.out.println(dt.getTime());
System.out.println(dt);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm a z");
df.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(df.format(dt));
df.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(df.format(dt));
And following is the output for this:
1389955549000
2014-01-17 16:15:49.0
17/01/2014 04:15 PM IST
17/01/2014 10:45 AM UTC
If you put this 1389955549000
in http://www.epochconverter.com/ then you get following output:
GMT: Fri, 17 Jan 2014 10:45:49 GMT
Your time zone: Friday, January 17, 2014 4:15:49 PM GMT+5.5
This is not the expected output, right. It is giving me time in millis which is -5:30 from the UTC time, so If I try to get time in IST timezone then it actually gives me time which is in UTC
Does anyone got idea where I am doing wrong?
--------------------------How I fixed it----------------------------
Based on suggestions from - Ako and Basil Bourque
Hibernate takes system timezone into consideration while fetching date/time fields from database. If you have stored DateTime
in UTC in database but your system time or for least your java app timezone is in other timezone(e.g, IST - Indian Standard Time) then hibernate thinks that DateTime
stored in database is also in IST and this is what causes whole problem.
For this as Basil suggested, use same timezones accross different servers. UTC should be preferred. Fix that I applied is that I added following code:
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
in ServletContextListener
which made my app timezone in UTC and now hibernate is fetching and storing dates as expected.