'how to create time slots in flutter/dart

I'm trying to create a list of time slots for building an appointment-related app. For example, build-time slots from 8 AM TO 10 PM with a 30-minute gap between each interval. I'm trying to achieve the result using the flutter/dart DateTime class

DateTime now = DateTime.now();
DateTime startTime = DateTime(now.year, now.month, now.day, 8, 0, 0);
DateTime endTime = DateTime(now.year, now.month, now.day, 22, 0, 0);
Duration step = Duration(minutes: 30);

List timeSlots = ['8:30','9:00','9:30']; // this is what I'm trying to achieve (final output)

Any help would be appriciated



Solution 1:[1]

You could do something like this:


void main() {
  DateTime now = DateTime.now();
  DateTime startTime = DateTime(now.year, now.month, now.day, 8, 0, 0);
  DateTime endTime = DateTime(now.year, now.month, now.day, 22, 0, 0);
  Duration step = Duration(minutes: 30);
  
  List<String> timeSlots = [];
  
  while(startTime.isBefore(endTime)) {
    
    DateTime timeIncrement = startTime.add(step);
    timeSlots.add(DateFormat.Hm().format(timeIncrement));
    startTime = timeIncrement;
  }
}

And if you print it out, you get this output:

[08:30, 09:00, 09:30, 10:00, 10:30, 11:00, 11:30, 12:00, 12:30, 13:00, 13:30, 14:00, 14:30, 15:00, 15:30, 16:00, 16:30, 17:00, 17:30, 18:00, 18:30, 19:00, 19:30, 20:00, 20:30, 21:00, 21:30, 22:00]

Note: I imported the intl package (import 'package:intl/intl.dart') so i could do the fomatting.

Solution 2:[2]

Making some slight modifications to Roman Jaquez's answer I got this

void main() {
  DateTime now = DateTime.now();
  DateTime startTime =
      DateTime(now.year, now.month, now.day, 0, 0, 0);
  DateTime endTime =
      DateTime(now.year, now.month, now.day, 23, 59, 0);
  Duration step = Duration(minutes: 1);

  List<BidSlot> timeSlots = [];

  while (startTime.isBefore(endTime)) {
    DateTime timeIncrement = startTime.add(step);
    timeSlots.add(BidSlot(
        startTime: DateFormat.Hm().format(timeIncrement),
        endTime: DateFormat.Hm().format(timeIncrement.add(
          Duration(minutes: 1),
        ))));
    startTime = timeIncrement;
  }
  print('timeslots ------------- timeSlots');
  timeSlots.forEach((e) => print('${e.startTime} == ${e.endTime}'));
}

Print result : [00:01 == 00:02, 00:02 == 00:03, 00:03 == 00:04, 00:04 == 00:05, 00:05 == 00:06 … 23:55 == 23:56, 23:56 == 23:57, 23:57 == 23:58, 23:58 == 23:59, 23:59 == 00:00]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roman Jaquez
Solution 2 Sean Gayle