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

后端 未结 15 1838
醉酒成梦
醉酒成梦 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:05

    You can equally have a class that returns the greetings.

    import java.util.Calendar;
    
    public class Greetings {
        public static String getGreetings()
        {
            Calendar c = Calendar.getInstance();
            int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
    
            if(timeOfDay < 12){
                return "Good morning";
            }else if(timeOfDay < 16){
                return "Good afternoon";
            }else if(timeOfDay < 21){
                return "Good evening";
            }else {
                return "Good night";
            }
        }
    }
    
    0 讨论(0)
  • 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<int, String> 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];
    }
    
    0 讨论(0)
  • 2020-12-14 02:09

    In kotlin use the following

    fun getCurrentTime(dateFormatInPut:String,myDate:String): Time {
            val sdf = SimpleDateFormat(dateFormatInPut, Locale.ENGLISH)
            val date = sdf.parse(myDate)
            val millis = date!!.time
            val calendar=Calendar.getInstance()
            calendar.timeInMillis=millis
            return when (calendar.get(Calendar.HOUR_OF_DAY)) {
                in 0..11 -> Time.Morning
                in 12..15 -> Time.AfterNoon
                else -> Time.Evening
            }
    
        }
    

    Here Time is enum class

    enum class Time {
    Morning,
    AfterNoon,
    Evening
    

    }

    0 讨论(0)
提交回复
热议问题