1

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.

4
  • In the DB is not 9:30 at all. In the DB is number of milliseconds and the 9:30 you see is just formatted value. The said formatting is based on timezone, there will be one in the DB and possibly one on the client connection used to show you the data. Commented Dec 27, 2014 at 14:52
  • I re-read your question. The point is that for your TZ the correct value for 09:30:00 is 30600000. Use the UTC as TZ if that is your point. Commented Dec 27, 2014 at 14:57
  • What database? What is data type of column, exactly? Commented Dec 27, 2014 at 18:31
  • I recommend you don’t use java.sql.Time. That class is poorly designed and long outdated. Instead use LocalTime from java.time, the modern Java date and time API. This will also eliminate your problem. Commented May 17, 2021 at 5:13

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.