Home > Software design >  how to create time slots in flutter/dart
how to create time slots in flutter/dart

Time:02-24

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

CodePudding user response:

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.

  • Related