How do you find period or times of the day in Java ?


  • I accidentally stumbled upon this feature in Java and although it might not be super useful, I have encountered a few use cases to identify the time or period of the day, such as morning, afternoon, or night and this feature has helped .
  • Starting Java 16 , the DateTimeFormatter class which is used for printing and parsing date-time objects has introduced a new format pattern for that called “B” to identify periods in a day, such as “in the morning” , “in the afternoon”, “in the evening” or “at night” .
String periodOfDay = DateTimeFormatter
                .ofPattern("B")
                .format(LocalDateTime.now());

        System.out.println(periodOfDay);
  • Output when i ran the above code snippet : “at night”
  • If you want to check the different period of a day in 24 hours , execute the below code
 public static void printDayPeriodsByHour()
    {
        final DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("hh B");
        for (int hour = 0; hour < 24; hour++)
        {
            final OffsetDateTime dateTime
                    = Instant.now().atOffset(ZoneOffset.UTC).withHour(hour);
            System.out.println("Hour " + hour + ": \"" + dateTimeFormat.format(dateTime) + "\"");
        }
    }
  • Output of the above code

Thank You ! Hope you enjoyed reading this.


If you are new to Java and looking for resources to learn, Head First Java: A Brain-Friendly Guide is a very good book .

Link to buy it on amazon: https://amzn.to/3Ikhp38

Leave a Reply