Show message based on
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"
}
}
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:
String greeting = null;
if(hours>=1 && hours<=11){
greeting = "Good Morning";
} else if(hours<=15){
greeting = "Good Afternoon";
} else if(hours<=20){
greeting = "Good Evening";
} else if(hours<=24){
greeting = "Good Night";
}
Toast.makeText(this, greeting, Toast.LENGTH_SHORT).show();
try this code(get hours and get minute methods in Date class are deprecated.)
private void getTimeFromAndroid() {
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
int hours = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
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();
}
}
using System;
namespace PF_Claas_Assign1
{
class Program
{
static void Main(string[] args)
{
DateTime Greeting = DateTime.Now;
if (Greeting.Hour >= 5 && Greeting.Hour < 12)
{
Console.WriteLine("Good morning....!");
}
else if (Greeting.Hour >= 12 && Greeting.Hour < 16)
{
Console.WriteLine("Good afternoon...!");
}
else if (Greeting.Hour >= 16 && Greeting.Hour < 20)
{
Console.WriteLine("Good evening...!");
}
else
{
Console.WriteLine("Good night...!");
}
}
}
}
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();
A cleaner method for detecting date would be.
//the time cannot go below zero, so if this case is true, it must be between 0 and 12
if(time <= 12)
{
return "Good Morning";
//it will only fall into this case if the time is greater than 12.
}else if(time < 16)
{
return "Good Afternoon";
}else if(time < 21)
{
return "Good Evening";
}else //it is guaranteed that the time will not exceed 24
//, and if the previous case are all false, it must be within 21 and 24
{
return "Good Night";
}