Home > Back-end >  How to get the next near future value to the current time in a list in Flutter?
How to get the next near future value to the current time in a list in Flutter?

Time:10-13

I have a store schedule that comes from the server. And I get the current time. I need to find the near future start_time to my current time in the list I am getting. For example, if the current time is 3:00 pm, I need to get the closest start_time, which is 5:00 pm. Tell me how to do it?

here I am accessing the key 'mon'

String dateFormat = DateFormat('EEE').format(timeNow).toLowerCase();
shopSchedule.templateFull![dateFormat]

the data I get

enter image description here

CodePudding user response:

You can do this to get closest time after now from your mon list:

String? selectedTime;
for (var element in mon) {
  if (selectedTime == null) {
    var now = DateTime.now();
    DateTime tempDate = DateFormat("yyyy-MM-dd hh:mm").parse(
        "${now.year}-${now.month}-${now.day} ${element["start_time"] as String}");

    if (tempDate.isAfter(now)) {
      selectedTime = element["start_time"];
    }
  } else {
    var now = DateTime.now();
    DateTime selectedDate = DateFormat("yyyy-MM-dd hh:mm")
        .parse("${now.year}-${now.month}-${now.day} $selectedTime");
    DateTime tempDate = DateFormat("yyyy-MM-dd hh:mm").parse(
        "${now.year}-${now.month}-${now.day} ${element["start_time"] as String}");

    if (tempDate.isBefore(selectedDate) && tempDate.isAfter(now)) {
      selectedTime = element["start_time"];
    }
  }
}
  • Related