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

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

    When I write

    Calendar c = Calendar.getInstance();
    int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
    

    I didn't get output and it doesn't show any error. Just the timeOfDay won't get assigned any value in the code. I felt it was because of some threading while Calendar.getInstance() is executed. But when I collapsed the lines it worked for me. See the following code:

    int timeOfDay = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    
    if(timeOfDay >= 0 && timeOfDay < 12){
            greeting.setText("Good Morning");
    }else if(timeOfDay >= 12 && timeOfDay < 16){
            greeting.setText("Good Afternoon");
    }else if(timeOfDay >= 16 && timeOfDay < 21){
            greeting.setText("Good Evening");
    }else if(timeOfDay >= 21 && timeOfDay < 24){
            greeting.setText("Good Morning");
    }
    

提交回复
热议问题