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

后端 未结 15 1841
醉酒成梦
醉酒成梦 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 02:09

    If somebody looking the same for Dart and Flutter: the code without if statements - easy to read and edit.

    main() {
      int hourValue = DateTime.now().hour;
      print(checkDayPeriod(hourValue));
    }
    
    String checkDayPeriod(int hour) {
      int _res = 21;
      Map dayPeriods = {
        0: 'Good night',
        12: 'Good morning',
        16: 'Good afternoon',
        21: 'Good evening',
      };
    
      dayPeriods.forEach(
        (key, value) {
          if (hour < key && key <= _res) _res = key;
        },
      );
    
      return dayPeriods[_res];
    }
    

提交回复
热议问题