Displays morning, afternoon, evening, and evening messages based on time in Java
•
Java
What do I want to do:
Display message based on
Good morning (12:00 ~ 12:00) > good noon (12:00 to 4:00) > good evening (4:00 to 9:00) > good night (9:00 to 6:00)
Code:
I use the 24-hour 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 the best way, if none is the best way
Solution
You should do this:
Calendar c = Calendar.getInstance(); int timeOfDay = c.get(Calendar.HOUR_OF_DAY); if(timeOfDay >= 0 && timeOfDay < 12){ Toast.makeText(this,Toast.LENGTH_SHORT).show(); }else if(timeOfDay >= 12 && timeOfDay < 16){ Toast.makeText(this,Toast.LENGTH_SHORT).show(); }else if(timeOfDay >= 16 && timeOfDay < 21){ Toast.makeText(this,Toast.LENGTH_SHORT).show(); }else if(timeOfDay >= 21 && timeOfDay < 24){ Toast.makeText(this,Toast.LENGTH_SHORT).show(); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码