I suggest: In your SQL database use either a proper datatype for an amount of time, a duration, or a char holding a duration in ISO 8601 format. In Java use Duration
(never LocalDateTIme
).
If your database has a datatype for a duration, consider using is, though do weigh the pros and cons. It probably means that you will have to transfer duration values to and from your database as text strings, which is not ideal. Some RDBMSs claim that their time
datatype can be used both for a time of day and for a duration, a hack, but if your database is happy to display 72 hours as 72:00
rather than 259200
, that’s definitely an advantage.
If you cannot or don’t want to use a proper datatype of your database, my second suggestion is ISO 8601 strings. The ISO 8601 format for a duration goes like PT12H
(for 12 hours; read as a period of time of 12 hours). 72 hours can be given as P3D
or PT72H
(assuming that we can safely convert 72 hours into 3 days; this is not always correct). While this format looks a bit weird, I still find it more readable than 259200
. varchar(13)
or so should suffice for your purpose.
In Java use a Duration
. If the duration comes out of your database as 72:00
, search for how to parse that into a Duration
, and search again for how to format it back. If it comes as PT12H
, the Duration
class parses that directly:
String durationStringFromDb = "PT12H";
Duration dur = Duration.parse(durationStringFromDb);
System.out.println(dur);
Output:
PT12H
The Duration
prints back in ISO 8601 format, its toString
method generates that. If you need the duration as seconds for some purpose:
System.out.println(dur.getSeconds());
43200
Edit: Or the other way, if you’ve got a number of seconds from somewhere:
int numberOfSeconds = 172800;
Duration dur = Duration.ofSeconds(numberOfSeconds);
System.out.println(dur);
PT48H
Links