You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DateTime字符串列表筛选为已过去与未过去两类?

日期时间列表的筛选实现

要完成这个筛选,核心思路是将字符串格式的日期时间转换为可比较的DateTime对象,再与当前时间对比,分别归类到两个列表中。以下是具体实现步骤(以Dart语言为例):

步骤1:依赖准备

首先需要引入intl包来处理日期格式解析,在pubspec.yaml中添加依赖:

dependencies:
  intl: ^0.18.1

步骤2:具体代码实现

import 'package:intl/intl.dart';

void main() {
  // 原始日期时间字符串列表
  List<String> dateTimeList = [
    "20-Feb-2023 at 10:30AM-Sun",
    "20-Feb-2023 at 07:30PM-Sun",
    "20-Feb-2023 at 07:30AM-Sun",
    "20-Feb-2023 at 06:30PM-Sun"
  ];

  // 定义匹配字符串的日期格式
  DateFormat dateFormat = DateFormat("dd-MMM-yyyy 'at' hh:mmaa-E", "en_US");
  
  List<String> timeHasGone = [];
  List<String> timeHasNotGone = [];
  
  DateTime now = DateTime.now();
  
  for (String dateStr in dateTimeList) {
    // 解析字符串为DateTime对象
    DateTime parsedDate = dateFormat.parse(dateStr);
    // 对比时间:如果解析出的时间早于当前时间,归为已过去列表,否则归为未过去列表
    if (parsedDate.isBefore(now)) {
      timeHasGone.add(dateStr);
    } else {
      timeHasNotGone.add(dateStr);
    }
  }
  
  // 输出结果
  print("已过去的时间列表:");
  print(timeHasGone);
  print("未过去的时间列表:");
  print(timeHasNotGone);
}

关键说明

  • 日期格式字符串"dd-MMM-yyyy 'at' hh:mmaa-E"完全匹配输入字符串的结构:
    • dd:两位日期
    • MMM:三位月份缩写(如Feb)
    • yyyy:四位年份
    • 'at':匹配字符串中的固定文本"at"
    • hh:12小时制的两位小时
    • mm:两位分钟
    • aa:AM/PM标识
    • E:三位星期缩写(如Sun)
  • 使用isBefore()方法直接对比DateTime对象,判断时间是否已过去
  • 如果需要处理时区差异,可以在解析时指定时区,或者将当前时间转换为对应时区后再对比

内容的提问来源于stack exchange,提问作者brijesh amipara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 11:56:34