There is no in-built feature in the date-time API to do so. Moreover, the legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time
, the modern date-time API* .
You can match the string with the regex pattern, \d{1,2}:\d{1,2}
which means one or two digits separated by a colon. If the match is successful, prepend 00:
to the string to convert it into HH:mm:ss
format.
Demo:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Optional;
import java.util.stream.Stream;
public class Main {
public static void main(String[] arg) {
// Test
Stream.of(
"01:48:00",
"48:00"
).forEach(s -> parseToTime(s).ifPresent(System.out::println));
}
static Optional<LocalTime> parseToTime(String s) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:m:s");
if (s.matches("\\d{1,2}:\\d{1,2}")) {
s = "00:" + s;
}
LocalTime time = null;
try {
time = LocalTime.parse(s, dtf);
} catch (DateTimeParseException e) {
System.out.println(s + " could not be parsed into time.");
}
return Optional.ofNullable(time);
}
}
Output:
01:48
00:48
Learn more about the modern date-time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.