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

14,515

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());
Share:
14,515
Ariyan
Author by

Ariyan

[Linux] [PHP , Python , Java , C ]

Updated on September 01, 2022

Comments

  • Ariyan
    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 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

  • pintxo
    pintxo over 12 years
    Not a good idea if you plan on using the time in any sort of calculation.