Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 599
Ariyan Avatar asked Dec 05 '11 10:12

Ariyan


1 Answers

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);
like image 99
Guillaume F. Avatar answered Nov 15 '22 17:11

Guillaume F.