By default, LocalTime#parse
parses the input string using DateTimeFormatter.ISO_LOCAL_TIME
whose format consists of:
- Two digits for the hour-of-day. This is pre-padded by zero to ensure two digits.
- A colon
- Two digits for the minute-of-hour. This is pre-padded by zero to ensure two digits.
- If the second-of-minute is not available then the format is complete.
- A colon
- Two digits for the second-of-minute. This is pre-padded by zero to ensure two digits.
- If the nano-of-second is zero or not available then the format is complete.
- A decimal point
- One to nine digits for the nano-of-second. As many digits will be output as required.
Since your input string is not in this format, you have encountered the exception. You can get around the exception by using a DateTimeFormatter
which allows you to specify a custom format. You can use H:m:s
as the format.
Demo:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:m:s", Locale.ENGLISH);
LocalTime t = LocalTime.parse("8:30:17", dtf);
System.out.println(t);
}
}
Output:
08:30:17
ONLINE DEMO
Note that for formatting, the single letter, H
works for single as well as a two-digit hour. Similar is the case with m
and s
as well.
Another thing you should always keep in mind is that the Date-Time formatting types are Locale
-sensitive and therefore you should always specify the applicable Locale
when using them. Check Never use SimpleDateFormat or DateTimeFormatter without a Locale to learn more about it.
Learn more about the modern Date-Time API* from Trail: Date Time.
* 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. Note that Android 8.0 Oreo already provides support for java.time
.