简体   繁体   English

如何在 flutter/dart 中创建时隙

[英]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.例如,构建时间段从早上 8 点到晚上 10 点,每个间隔之间有 30 分钟的间隔。 I'm trying to achieve the result using the flutter/dart DateTime class我正在尝试使用 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任何帮助都会得到帮助

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:如果你把它打印出来,你会得到这个 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.注意:我导入了intl package (import 'package:intl/intl.dart') 所以我可以做格式化。

Making some slight modifications to Roman Jaquez's answer I got this对 Roman Jaquez 的回答做了一些细微的修改,我得到了这个

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM