How to Parse Time in Java

To parse time in Java, the most trouble-free and programatic way is using the parse method of the LocalTime class like this:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class TimeParse {
    public static void main(String[] args) {
        String inputStr = "Time is 11 minutes past 11PM.";
        String pattern = "'Time is 'm' minutes past 'ha.";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
        LocalTime time = LocalTime.parse(inputStr, dtf);
        System.out.println(time);
    }
}

You will have to define first a pattern and also the formatting. After that everything will work like a charm.

Comments

So empty here ... leave a comment!

Leave a Reply

Sidebar



%d bloggers like this: