Best Way to store time (Only Time and Not date) in database
Solution 1
It's ok to store time as time-in-milliseconds from null-date (January 1, 1970, 00:00:00 GMT). You will be able easily made compare operations on this long data field in the DB.
Solution 2
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);
Solution 3
You can store as a normal String
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
String time = sdf.format(Calendar.getInstance());
Comments
-
Ariyan over 1 year
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 aLong
number.
But When i need only the Time and not the Date and Time what is the best way to store it?
I'm UsingSQLite
andMS Access
as DBMS.Thanks
-
pintxo over 12 yearsNot a good idea if you plan on using the time in any sort of calculation.