【发布时间】:2015-02-19 18:51:23
【问题描述】:
我想做什么::
显示消息基于
- 早上好(12am-12pm)
- 中午后好(12pm -4pm)
- 晚上好(下午 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 题外话,不应该是 AND && ,您使用的是 OR ||这将导致所有案例(小时 >= 1)都属于早安案例?
-
你应该知道,小时在
0和23之间的范围内:getHours()。 -
@Devrath 我已经更新了答案以考虑到 12:59。
-
仅供参考,
java.util.Date、java.util.Calendar和java.text.SimpleDateFormat等麻烦的日期时间类现在已被 java.time 类所取代。大多数 java.time 功能在 ThreeTen-Backport 项目中被反向移植到 Java 6 和 Java 7。进一步适用于ThreeTenABP 中的早期 Android (How to use ThreeTenABP…。