I have a task of converting, time stored on one of my DB(Sql Server)'s table's column to a specified timezone. The column always contains time in UTC timezone.
The problem I am facing is, when hibernate READS the column and sets it to my entity class, it sets the time in the application server's timezone.
For Eg: if DB has value - 07 Jul 2012 10:30 (which is actually UTC), the hibernate sets the mapped date field as 07 Jul 2012 10:30 PST (assuming the JVM is running at PST).
Now if this date gets converted to any other timezone.. say GMT+5:30, i get unexpected result
To fix the above issue... i wrote the following code
//Reading the DB time (which does not have timezone info)
Date dbDate = entityObj.getDBUtcDate();
//Setting GMT timezone to the date, without modifying the date
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.set(dbDate.getYear(), dbDate.getMonth(), dbDate.getDate()..., dbDate.getMinutes());
Date utcDate = c.getTime();
Using above code.. I could get the DB stored date back in UTC timezone, but when I did conversion to some other timezone(say GMT+5:30) using below logic
Calendar outCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+5:30"));
outCal.setTimeInMillis(utcDate.getTime());
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, outCal.get(Calendar.YEAR));
cal.set(Calendar.MONTH, outCal.get(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, outCal.get(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, outCal.get(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, outCal.get(Calendar.MINUTE));
cal.set(Calendar.SECOND, outCal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, outCal.get(Calendar.MILLISECOND));
//Converted date
Date pstTime = cal.getTime();
//Converted time mill seconds
long timeMilSec = pstTime.getTime();
The time millisecond of the converted date started coming as negative (-54672...), which seems to be representing an invalid time.
My question here is How can i restore the timezone information from DB (without having to have any extra column in DB to specifically store timezone information)?
OR
How can i convert a DB time into a time having a specified timezone(UTC)?
PS: I expect the output in the form of java.util.Date/ Calendar because i need to do one more conversion on this date
Please help me resolving this issue