How can I show greetings like Good Moring, afternoon or evening base on users time in flutter
Fetch the current time and Parse it and fetch only hours.
var timeNow = DateTime.now().hour;
Now, our timeNow a variable has the hour value in integer format we only need to check the condition and Change messages according to time like this
String greetingMessage(){ var timeNow = DateTime.now().hour; if (timeNow <= 12) { return 'Good Morning'; } else if ((timeNow > 12) && (timeNow <= 16)) { return 'Good Afternoon'; } else if ((timeNow > 16) && (timeNow < 20)) { return 'Good Evening'; } else { return 'Good Night'; }}
And use as
String greetingMes = greetingMessage();
TimeOfDay.now().period; // This will return DayPeriod.am or DayPeriod.pm, you can show the greeting message accordingly
Link: https://api.flutter.dev/flutter/material/TimeOfDay/period.html
import 'package:flutter/material.dart';void main(){ TimeOfDay day = TimeOfDay.now(); switch(day.period){ case DayPeriod.am: print('its morning'); break; case DayPeriod.pm: print('its evening/night'); }}