Search code examples
javalocaltime

Converting my string to LocalTime with patterns


I wanted to convert my string to LocalTime format

    String s = "1時30分:00";
    String ss = s.replace("時", ":").replace("分", ":");
    DateTimeFormatter timeColonFormatter = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("hh:mm a").toFormatter(Locale.JAPAN);
    System.out.println(timeColonFormatter);
    LocalTime colonTime = LocalTime.parse("3:30 am", timeColonFormatter);
    System.out.println(colonTime);

I received error:

Exception in thread "main" java.time.format.DateTimeParseException: Text '3:30 ' could not be parsed at index 0

Expected output:

3:30 AM


Solution

  • In your pattern you have a two-digit hour, and since your locale is Japan, you have to use the Japanese equivalent of AM/PM, which are 午前 / 午後, respectively, e.g.:

    LocalTime.parse("03:30 午前", timeColonFormatter);
    LocalTime.parse("03:30 午後", timeColonFormatter);
    

    You can accept single-digits times, too, with the pattern "h:mm a".

    Edit: You can also parse the Japanese time directly, without need to convert to semi-international format, e.g. using the pattern "h時mm分 a":

    LocalTime colonTime = LocalTime.parse("3時30分 午前", timeColonFormatter);
    

    Or, in the correct Japanese order, with the pattern "ah時mm分":

    LocalTime colonTime = LocalTime.parse("午前3時30分", timeColonFormatter);