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
相关产品推荐
相关产品推荐

