Showing Morning, afternoon, evening, night message based on Time in java

后端 未结 15 1860
醉酒成梦
醉酒成梦 2020-12-14 01:39

What i am trying to do::

Show message based on

  • Good morning (12am-12pm)
  • Good after noon (12pm -4pm)
  • Good evening
15条回答
  •  情话喂你
    2020-12-14 01:44

    Using Time4J (or Time4A on Android) enables following solutions which do not need any if-else-statements:

    ChronoFormatter parser =
        ChronoFormatter.ofTimePattern("hh:mm a", PatternType.CLDR, Locale.ENGLISH);
    PlainTime time = parser.parse("10:05 AM");
    
    Map table = new HashMap<>();
    table.put(PlainTime.of(1), "Good Morning");
    table.put(PlainTime.of(12), "Good Afternoon");
    table.put(PlainTime.of(16), "Good Evening");
    table.put(PlainTime.of(21), "Good Night");
    ChronoFormatter customPrinter=
        ChronoFormatter
          .setUp(PlainTime.axis(), Locale.ENGLISH)
          .addDayPeriod(table)
          .build();
    System.out.println(customPrinter.format(time)); // Good Morning
    

    There is also another pattern-based way to let the locale decide in a standard way based on CLDR-data how to format the clock time:

    ChronoFormatter parser =
        ChronoFormatter.ofTimePattern("hh:mm a", PatternType.CLDR, Locale.ENGLISH);
    PlainTime time = parser.parse("10:05 AM");
    
    ChronoFormatter printer1 =
        ChronoFormatter.ofTimePattern("hh:mm B", PatternType.CLDR, Locale.ENGLISH);
    System.out.println(printer1.format(time)); // 10:05 in the morning
    
    ChronoFormatter printer2 =
        ChronoFormatter.ofTimePattern("B", PatternType.CLDR, Locale.ENGLISH)
            .with(Attributes.OUTPUT_CONTEXT, OutputContext.STANDALONE);
    System.out.println(printer2.format(time)); // morning
    

    The only other library known to me which can also do this (but in an awkward way) is ICU4J.

提交回复
热议问题