EDIT: take a look at this other stackoverflow post about why one should prefer using the Java 8 java.time
classes over Calendar
or Date
In your instance, in order to parse an input in the form "HH:mm", you can create a DateTimeFormatter
and use the static method LocalTime.parse(inputString, dateTimeFormatter)
to get a LocalTime object
For example:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
LocalTime time = LocalTime.parse(timeInputString, formatter);
Take a look at the Java documentation for DateTimeFormatter for more information on the patterns for years, days, or whatever.
If you're wanting to get both the date and time from a string such as "10:50", you won't be able to using the LocalDateTime.parse
method because it can't obtain the date from an "HH:mm" string. So the way around this is to create the time off of LocalTime.parse
as shown above, and then get the current date using the static method LocalDate.now();
And then combine those two results into a LocalDateTime
object using it's static factory method LocalDateTime.of(date, time)
For example:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
LocalTime time = LocalTime.parse(timeInputString, formatter);
LocalDate date = LocalDate.now();
LocalDateTime dateTime = LocalDateTime.of(date, time);