Tolga Yılmaz
Tolga Yılmaz

Reputation: 518

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.

Upvotes: 0

Views: 506

Answers (1)

esentis
esentis

Reputation: 4666

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 ^^

Upvotes: 1

Related Questions