How to convert String containing date and time to LocalTime variable

3.7k Views Asked by At

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

6

There are 6 best solutions below

0
On BEST ANSWER

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);
0
On

You may just use String#split if you are sure the format of string is already the same.

String s = "2017-09-13 00:01:00";
String[] frags = s.split(" ");
System.out.println(frags[frags.length - 1]);

Output:

00:01:00

Add some checks if you need.

0
On

This might help you ::

Or you can use the split function as written in another answer.

Here your string has been converted to date and calendar objects. Now you can do anything with the objects.

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class test {
    public static void main(String[] args) throws IOException, ParseException {
        String timestamp = "2017-09-13 00:01:00";
        DateFormat format = new SimpleDateFormat("yyyy-dd-mm HH:mm:ss");
        Date date = format.parse(timestamp);
        System.out.println(date);

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        System.out.println(date.getTime());
        System.out.println(date.getHours());
        System.out.println(date.getMinutes());
        System.out.println(date.getSeconds());
    }
}
0
On

Use DateTimeFormatter(java.time.format.DateTimeFormatter) and LocalDateTime

    String s = "2017-09-13 00:01:00";

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    LocalTime start = LocalDateTime.parse(s,dtf).toLocalTime();
0
On

You need to use the new java datetime API. I.e. configure the right parser. Here it is:

String original = "2017-09-13 00:01:15";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .parseCaseInsensitive()
        .append(DateTimeFormatter.ISO_LOCAL_DATE)
        .appendLiteral(' ') // this is what you won't find among the default formatters
        .append(DateTimeFormatter.ISO_LOCAL_TIME)
        .toFormatter();
LocalTime time = LocalTime.parse(original, formatter); // it's cool now
System.out.println(time); // prints 00:01:15
1
On

If the format yyyy-mm-dd hh:mm:ss is fixed, this would probably be the fastest answer so far, since it avoids any kind of added string parsing or splitting:

LocalTime.parse(strings[0].substring(11))