I know I didn't ask this but is HHmmss.SSSSS what I should be using?
You asked now, and thanks for asking.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HHmmss.SSSSS");
String timeString = "121212.00000";
LocalTime time = LocalTime.parse(timeString, dtf);
System.out.println(time);
This prints
12:12:12
LocalTime
from java.time
has precision of nanoseconds (up to 9 decimals on the seconds) but its toString
method doesn’t print the fraction if it is zero. 121212.34567
, for example, is parsed into 12:12:12.345670
. Let’s try your string with the dash too, 1-1212.00000
. It results in a java.time.format.DateTimeParseException: Text '1-1212.00000' could not be parsed at index 0
. As you had expected, the formatter refuses to parse the hours when the second digit is a dash. This also means that you have good validation in the parsing, so you no longer need any regular expression (regex).
The Timestamp
and SimpleDateFormat
classes are both long outdated, though the latter is the more troublesome of the two. Also SimpleDateFormat
supports only millisecond precision, there is no way it could parse seconds with 5 decimals correctly. Find the modern replacements in the java.time
package. Use DateTimeFormatter
for parsing. I assume you wanted to save a time-of-day without a date into an SQL database. If so, use an SQL datatype of time
and a LocalTime
in Java. PreparedStatement.setObject()
will accept the LocalTime
for saving. If your database column has type timestamp
and cannot be changed, use LocalDateTime
instead.
And while Andreas in a comment has explained why your suggested format pattern string of HHmmss.SSSSS
would not work with SimpleDateFormat
, it does work with DateTimeFormatter
. Here uppercase S
means fraction of second, so SSSSS
means five decimals (otherwise many of the format pattern letters have the same meaning to both formatters, only not all).
Question: can I use java.time
in Java 6?
Yes, most of the above will work with your JavaSE 1.6, only not PreparedStatement.setObject()
. You will need to add ThreeTen Backport to your project. This is the backport of java.time
to Java 6 and 7 (“ThreeTen” becuase java.time
was first described in JSR-310). See the link below.
For saving to your SQL database, you will need to convert to an old-fashioned java.sql.Timestamp
or java.sql.Time
. For a time stamp you also need a date. For example:
LocalDate epochDate = LocalDate.ofEpochDay(0);
Timestamp timeToSave
= DateTimeUtils.toSqlTimestamp(LocalDateTime.of(epochDate, time));
I took the epoch date of January 1, 1970, since this is also what a proper parsing of your time string into a Timestamp
would have given you. I figure your DICOM can probably give you a date that you want to use instead. DateTimeUtils
also has a toSqlTime
method for converting LocalTime
to java.sql.Time
. Link to the documentation below.
Links