Showing Morning, afternoon, evening, night message based on Time in java
You should be doing something like:
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();}
For anyone who is looking for the latest Kotlin syntax for @SMA's answer, here is the helper function :
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" } }
I would shorten your if/elseif
statement to:
String greeting = null;if(hours>=1 && hours<=12){ greeting = "Good Morning";} else if(hours>=12 && hours<=16){ greeting = "Good Afternoon";} else if(hours>=16 && hours<=21){ greeting = "Good Evening";} else if(hours>=21 && hours<=24){ greeting = "Good Night";}Toast.makeText(this, greeting, Toast.LENGTH_SHORT).show();