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

Flutter中如何将毫秒时间戳列表转为hh:mm a格式字符串列表

如何将Flutter中List毫秒时间戳列表转为"hh:mm a"格式字符串列表?

你可以通过map方法替代forEach直接生成目标字符串列表,同时优化DateFormat实例的创建逻辑,避免重复初始化。具体修改如下:

完整实现代码

import 'package:intl/intl.dart';

void main() {
  List<int> startTimeInInt = [1665392445000, 1665403245000, 1665405045000, 1665406845000, 1665410445000, 1665419445000, 1665574255000, 1665747055000, 1665390645000];

  // 提前初始化格式化工具,避免重复创建实例
  final timeFormatter = DateFormat("hh:mm a");
  
  // 转换并生成目标列表
  List<String> newTime = startTimeInInt.map((timestamp) {
    final dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
    return timeFormatter.format(dateTime);
  }).toList();

  // 验证结果
  print(newTime);
}

关键说明

  • 使用map方法遍历原时间戳列表,对每个元素执行转换逻辑,返回包含格式化字符串的Iterable<String>
  • 调用toList()将Iterable转换为List<String>,得到你需要的最终结果
  • 将DateFormat实例移到循环外部初始化,避免每次遍历都创建新的格式化对象,提升代码性能

内容的提问来源于stack exchange,提问作者Ashu Upadhyay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:10:25