Flutter How to check there is any time within certain time?


I want to check there is any time within certain time. Clearly, I got a list:

List<String> timeSlots = [];

This list returning me times like this: [08:30,09:00,...,22:00]

And I got current phone time. And I am creating listViewBuilder.

I just want to check if current phone time between 08:30-09:00 and I want to set my Card color which it’s listViewBuilder's returning widget.


What I would do is use the isAfter & isBefore methods of DateTime. So you will have to create DateTimes out of the first two times :

  List<String> timeSlots = ["08:30", "09:00", "22:00"];

  DateTime currentTime = DateTime.now();

  DateTime date1 = DateTime.parse(
      "${currentTime.year}-${currentTime.month < 10 ? '0${currentTime.month}' : currentTime.month}-${currentTime.day} ${timeSlots[0]}:00");
  DateTime date2 = DateTime.parse(
       "${currentTime.year}-${currentTime.month < 10 ? '0${currentTime.month}' : currentTime.month}-${currentTime.day} ${timeSlots[1]}:00");

  print(currentTime.isAfter(date1) && currentTime.isBefore(date2));

There may be other prettier ways though ^^

Answered By – esentis

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *