To format 24 hours form time into 12 hours format, We can use letter "a" in the formatter. For time period from "00:00" hours to "11:59", it prints "AM".
LocalTime date1 = LocalTime.parse("00:00");
LocalTime date2 = LocalTime.parse("11:59");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm a");
String date1Str = formatter.format(date1);
String date2Str = formatter.format(date2);
System.out.println(date1Str);
System.out.println(date2Str);
Output :
12:00 AM
11:59 AM
In Java 16 , a new literal "B" (or BBBB or BBBBB) is added. It describes the time in human readable way. It prints as follows.
00:00 - midnight
00:01 to 05:59 - at night
06:00 to 11:59 - in the morning
12:00 to 17:59 - in the afternoon
18:00 to 20:59 - in the evening
21:00 to 23:59 - at night
LocalTime date1 = LocalTime.parse("00:00");
LocalTime date2 = LocalTime.parse("05:10");
LocalTime date3 = LocalTime.parse("08:10");
LocalTime date4 = LocalTime.parse("13:59");
LocalTime date5 = LocalTime.parse("18:10");
LocalTime date6 = LocalTime.parse("22:59");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm B");
String date1Str = formatter.format(date1);
String date2Str = formatter.format(date2);
String date3Str = formatter.format(date3);
String date4Str = formatter.format(date4);
String date5Str = formatter.format(date5);
String date6Str = formatter.format(date6);
System.out.println(date1Str);
System.out.println(date2Str);
System.out.println(date3Str);
System.out.println(date4Str);
System.out.println(date5Str);
System.out.println(date6Str);
Output:
12:00 midnight
05:10 at night
08:10 in the morning
01:59 in the afternoon
06:10 in the evening
10:59 at night
Please let me know your opinion in the comments below.
Happy Coding 😀