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
I would shorten your
if/elseif
statement to:When I write
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 whileCalendar.getInstance()
is executed. But when I collapsed the lines it worked for me. See the following code:You should be doing something like:
Using Time4J (or Time4A on Android) enables following solutions which do not need any if-else-statements:
There is also another pattern-based way to let the locale decide in a standard way based on CLDR-data how to format the clock time:
The only other library known to me which can also do this (but in an awkward way) is ICU4J.
try this code(get hours and get minute methods in Date class are deprecated.)