Best Way to store time (Only Time and Not date) in database

RYN picture RYN · Dec 5, 2011 · Viewed 13.2k times · Source

I'm developing an application using Java (J2SE).
I need to store a Time in database (e.g. 16:30:12).
When I need to store date (Or date+time) I convert it to Unix timestamp and I store it as a Long number.
But When i need only the Time and not the Date and Time what is the best way to store it?
I'm Using SQLite and MS Access as DBMS.

Thanks

Answer

Guillaume F. picture Guillaume F. · Jan 13, 2016

A better way since Java 8, or by using the Joda-Time library in earlier versions:

Use the LocalTime class and extract the number of seconds since midnight. You can store this as a three bytes number (0 to 86399) in your database (instead of a eight bytes datetime).

https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html

LocalTime time = LocalTime.parse("12:34:45");
int secondOfDay = time.toSecondOfDay();
// Save to database

To reverse:

// Get from database
LocalTime time = LocalTime.ofSecondOfDay(secondOfDay);