Show message based on
You can equally have a class that returns the greetings.
import java.util.Calendar;
public class Greetings {
public static String getGreetings()
{
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if(timeOfDay < 12){
return "Good morning";
}else if(timeOfDay < 16){
return "Good afternoon";
}else if(timeOfDay < 21){
return "Good evening";
}else {
return "Good night";
}
}
}
If somebody looking the same for Dart and Flutter: the code without if statements - easy to read and edit.
main() {
int hourValue = DateTime.now().hour;
print(checkDayPeriod(hourValue));
}
String checkDayPeriod(int hour) {
int _res = 21;
Map<int, String> dayPeriods = {
0: 'Good night',
12: 'Good morning',
16: 'Good afternoon',
21: 'Good evening',
};
dayPeriods.forEach(
(key, value) {
if (hour < key && key <= _res) _res = key;
},
);
return dayPeriods[_res];
}
In kotlin use the following
fun getCurrentTime(dateFormatInPut:String,myDate:String): Time {
val sdf = SimpleDateFormat(dateFormatInPut, Locale.ENGLISH)
val date = sdf.parse(myDate)
val millis = date!!.time
val calendar=Calendar.getInstance()
calendar.timeInMillis=millis
return when (calendar.get(Calendar.HOUR_OF_DAY)) {
in 0..11 -> Time.Morning
in 12..15 -> Time.AfterNoon
else -> Time.Evening
}
}
Here Time is enum class
enum class Time {
Morning,
AfterNoon,
Evening
}