在java中显示基于时间的早上,下午,晚上,晚上消息

新手上路,请多包涵

我想做什么::

显示消息基于

  • 早上好(中午 12 点至中午 12 点)
  • 中午后(中午 12 点 -4 点)
  • 晚上好(下午 4 点到晚上 9 点)
  • 晚安(晚上 9 点到早上 6 点)

代码::

我使用 24 小时格式来获取此逻辑

private void getTimeFromAndroid() {
        Date dt = new Date();
        int hours = dt.getHours();
        int min = dt.getMinutes();

        if(hours>=1 || hours<=12){
            Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
        }else if(hours>=12 || hours<=16){
            Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
        }else if(hours>=16 || hours<=21){
            Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
        }else if(hours>=21 || hours<=24){
            Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
        }
    }


问题:

  • 这是最好的方法吗,如果不是,那是最好的方法

原文由 Devrath 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 611
2 个回答

你应该做这样的事情:

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

if(timeOfDay >= 0 && timeOfDay < 12){
    Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 12 && timeOfDay < 16){
    Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 16 && timeOfDay < 21){
    Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 21 && timeOfDay < 24){
    Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
}

原文由 SMA 发布,翻译遵循 CC BY-SA 3.0 许可协议

对于正在为@SMA 的答案寻找最新 Kotlin 语法的任何人,这里是辅助函数:

 fun getGreetingMessage():String{
    val c = Calendar.getInstance()
    val timeOfDay = c.get(Calendar.HOUR_OF_DAY)

    return when (timeOfDay) {
           in 0..11 -> "Good Morning"
           in 12..15 -> "Good Afternoon"
           in 16..20 -> "Good Evening"
           in 21..23 -> "Good Night"
           else -> "Hello"
      }
    }

原文由 Vishal Sonawane 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题