Search code examples
javaswingdatensdateformatterjodatime

How to format a LocalTime variable


I am quite new to Java windowbuilder, and this is part of my first project.

String starttime = JOptionPane.showInputDialog(null, "What time would you like to start your revision ? (ie:12:24) ");

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm");
LocalTime start = LocalTime.parse(starttime,dtf);

I want to convert the format of start from ("HH:mm:ss..etc") to ("HH:mm"), but I get an error for the LocalTime.parse for some reason. Any suggestions what I should do.

I'm using Joda Time


Solution

  • You're incorrectly referencing ofPattern in java.time. Use JodaTime's forPattern

    DateTimeFormatter dtf = DateTimeFormat.forPattern("HH:mm");
    LocalTime start = LocalTime.parse(starttime, dtf);
    System.out.println(dtf.print(start));
    

    or simply

    System.out.println(LocalTime.parse(startTime).toString("HH:mm"));