Reputation: 137
In my program I need to read a Time value from the database and then convert that value to milliseconds. I do it like this :
Time t = getTimeFromDatabase();
long millis = t.getTime();
The problem is that the value of millis
corresponds to time value which is 1 hour earlier than what is entered in the database.
For example: let's say that the value in the DB is 09:30:00. So if I do this:
Time t = getTimeFromDatabase();
System.out.println(t.toString);
System.out.println(t.getTime);
Output would be:
09:30:00
30600000
Now... 09:30:00 is ok. That's how it is in the DB.
But 30600000 / 3600000 = 8.5
(3600000 is milliseconds per hour). Which means that this value in milliseconds corresponds to 08:30:00.
The correct value for 09:30:00 should be 34200000.
My question is how can I get correct value regardless of time zone (I am in UTC +1, so I guess that this has something to do with my problem).
I have tried with other time values but it is always the same (1 hour earlier).
Thanks in advance.
Upvotes: 1
Views: 1048
Reputation: 579
When you parse the data from DB into a Time object, you should use a formatter, and set the proper time zone.
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = timeFormat.parse(dataFromDB); // dataFromDB is a "09:30:10" like String
System.out.println(timeFormat.format(date)); // will print time in HH:mm:ss format
System.out.println(date.getTime()); // will print milliseconds
Upvotes: 1