I was converting a sequence of String
s which contained three different times
Start, end and duration
"00:01:00,00:02:00,00:01:00"
to LocalTime
variables:
for (final String str : downtime) {
final DependencyDownTime depDownTime = new DependencyDownTime ();
final String[] strings = str.split (",");
if (strings.length == 3) {
LocalTime start = LocalTime.parse (strings[0]);
depDownTime.setStartTime (start);
LocalTime end = LocalTime.parse (strings[1]);
depDownTime.setEndTime (end);
Duration duration = Duration.between (start, end);
depDownTime.setDuration (duration);
downTimes.add (depDownTime);
}
}
The String
being parsed has changed and now includes a date. 2017-09-13 00:01:00
How do I remove the date string keeping only the time?
I have tried to use the SimpleDateFormat
final DateFormat dateFormat = new SimpleDateFormat ("HH:mm:ss");
LocalTime start = LocalTime.parse (dateFormat.format (strings[0]));
depDownTime.setStartTime (start);
But I get a java.lang.IllegalArgumentException
You can use a
DateTimeFormatter
, then parse it to aLocalDateTime
and extract theLocalTime
from it:Or parse it directly to a
LocalTime
, using thefrom
method:Or (even simpler):