What data type can store the date and time format YYYY-mm-DD HH:MM:SS and just the time HH:MM:SS in the database. I found only two solutions - one in the form of strings, but unfortunately it has its drawbacks - the inability to sort information with a SQL query. And the second is in the form of java.SQL.Date, but with its help I only get YY-mm-DD in the database (maybe I do not use it correctly). What other ways besides those I mentioned? And which is better to use?
2 answers
it is best to store the date in long using new Date().getTime() or Calendar.getInstance().getTimeInMillis() then everything can be transformed into any format using SimpleDateFormat
Depends on the database and the specific task. The base can have native data types for dates, times, dates and times, taking into account time zones and without it, for a simple UNIX epoch timestamp (which is like a long from an adjacent answer). Usually you will want to store time in UTC or Unix epoch time.
Storing as a string is usually not the best solution, but a forced one, if we are talking about some string key-value database. If you have to do this, follow the ISO 8601 standard and reduce the time to UTC.
Inside Java, never write bicycles to work with dates and times. Avoid the Calendar class.
In Java 7 and earlier (if for some reason you have to write on it) use Joda-Time .
In Java 8+, use the new Java Time API ( java.time ) , (which is based on Joda-Time) or use Joda-Time again.
In the string representation with the desired time zone, translate the date when you need to show it to the user.
Why you need to be careful when working with time is well described on Habré: