Search code examples
javatimesimpledateformatjava-timelocaltime

How to convert String containing date and time to LocalTime variable


I was converting a sequence of Strings 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


Solution

  • You can use a DateTimeFormatter, then parse it to a LocalDateTime and extract the LocalTime from it:

    String input = "2017-09-13 00:01:00";
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    LocalTime time = LocalDateTime.parse(input, fmt).toLocalTime();
    

    Or parse it directly to a LocalTime, using the from method:

    LocalTime time = LocalTime.from(fmt.parse(input));
    

    Or (even simpler):

    LocalTime time = LocalTime.parse(input, fmt);