如何在Dart中按用户时区的指定时段过滤列表?
按指定时区时段过滤时间列表
原始数据(UTC时区)
final userTimezone = currentUser?.timezone; // "America/New_York" final list = [ {id: 1, name: 'thing 1', startTime: 2023-07-14 07:30:00.000Z}, {id: 2, name: 'thing 2', startTime: 2023-07-20 08:00:00.000Z}, {id: 3, name: 'thing 3', startTime: 2023-07-25 20:15:00.000Z}, {id: 4, name: 'thing 4', startTime: 2023-07-26 13:00:00.000Z}, ];
需求
按用户时区(America/New_York)的8:00-19:00时段过滤列表,保留startTime落在该时段内的条目。
现有代码问题分析
你当前的代码存在几个关键错误:
- 时区基准错误:
toLocal()会将UTC时间转换为设备本地时区,而非用户指定的America/New_York时区,导致判断逻辑完全偏离需求。 - 不必要的分秒限制:强制要求分秒必须为0,过滤掉了所有非整点的有效时间(比如
thing 3的16:15)。 - 字段不匹配:原始列表只有
startTime字段,但代码中误用了endAt,属于笔误。 - 逻辑过严:要求起止时间都必须在8-19点,但需求仅需判断
startTime是否在该区间。
正确解法
要实现指定时区的时间判断,需借助intl包的时区转换能力。
步骤1:添加依赖
在pubspec.yaml中添加intl依赖:
dependencies: intl: ^0.18.1
步骤2:实现过滤逻辑
import 'package:intl/intl.dart'; void main() { final userTimezone = "America/New_York"; final list = [ {"id": 1, "name": 'thing 1', "startTime": DateTime.parse("2023-07-14T07:30:00.000Z")}, {"id": 2, "name": 'thing 2', "startTime": DateTime.parse("2023-07-20T08:00:00.000Z")}, {"id": 3, "name": 'thing 3', "startTime": DateTime.parse("2023-07-25T20:15:00.000Z")}, {"id": 4, "name": 'thing 4', "startTime": DateTime.parse("2023-07-26T13:00:00.000Z")}, ]; // 初始化指定时区的格式化器 final timeFormatter = DateFormat.yMd().add_Hms().add_z(); timeFormatter.timeZoneName = userTimezone; final filteredList = list.where((item) { final utcStartTime = item["startTime"] as DateTime; // 将UTC时间转换为目标时区的时间 final nyTime = timeFormatter.parse(timeFormatter.format(utcStartTime)); // 判断小时是否在8:00-19:00区间内(包含8点和19点) return nyTime.hour >= 8 && nyTime.hour <= 19; }).toList(); // 输出筛选结果 filteredList.forEach((item) { print("${item["name"]}: ${timeFormatter.format(item["startTime"] as DateTime)}"); }); }
代码说明
- 通过
DateFormat指定目标时区,实现UTC时间到America/New_York时区的精准转换。 - 仅判断转换后的时间小时数是否在8-19之间,无需限制分秒,完全匹配需求。
- 修正了字段不匹配的问题,仅使用
startTime进行判断。
运行结果
最终会筛选出符合条件的条目:
- thing 3: 7/25/2023 4:15:00 PM EDT
- thing 4: 7/26/2023 9:00:00 AM EDT
内容的提问来源于stack exchange,提问作者nyphur
相关产品推荐
相关产品推荐

