The best way to save time (only time and not date) in the database

I am developing an application using Java (J2SE).
I need to save a time database in a database (e.g. 16:30:12).
When I need to save a date (or date + time), I convert it to a Unix timestamp, and I store it as a Long number.
But when I only need time, not date and time, what is the best way to save it?
I use SQLite and MS Access as a DBMS.

thanks

+6
source share
3 answers

It is good to store time as time-in-milliseconds from the zero date (January 1, 1970, 00:00:00 GMT). You can easily perform comparison operations in this long data field in the database.

+2
source

The best way with Java 8 or using the Joda-Time library in earlier versions:

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

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 

Cancel:

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

You can save as regular String

 SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss"); String time = sdf.format(Calendar.getInstance()); 
+1
source

Source: https://habr.com/ru/post/903095/


All Articles