What i am trying to do::
Show message based on
- Good morning (12am-12pm)
- Good after noon (12pm -4pm)
- Good evening (4pm to 9pm)
- Good night ( 9pm to 6am)
CODE::
I used 24-hr format to get this logic
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();
}
}
Question:
- Is this this best way of doing it, If no which is the best way
You determine if it is in the first interval, and then all other intervals depends on the upper limit. So you can make it even shorter:
java.time
I would advise to use Java 8 LocalTime.
Maybe create a class like this to handle your time of day problem.
For anyone who is looking for the latest Kotlin syntax for @SMA's answer, here is the helper function :