Show message based on
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(); } }
For example, “Good morning” is generally used from 5:00 a.m. to 12:00 p.m. whereas “Good afternoon” time is from 12:00 p.m. to 6:00 p.m. “Good evening” is often used after 6 p.m. or when the sun goes down.
Early afternoon: noon-3 p.m. Mid-afternoon: 2-4 p.m. Late- afternoon: 3-6 p.m. Evening: 6-9 p.m.
Example. int time = 22; if (time < 10) { System.out.println("Good morning."); } else if (time < 20) { System.out.println("Good day."); } else { System.out.println("Good evening."); } // Outputs "Good evening."
Good morning is from 12 am to 12 pm. From 12pm to around 5pm we say good afternoon. From 5pm to 12pm it is good evening.
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" } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With