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

Flutter中如何将MM/dd/yyyy, HH:mm:ss a格式字符串转回毫秒时间戳

Flutter 日期字符串反向转毫秒时间戳实现方案

你只需要用和格式化时完全相同的日期格式规则解析字符串,再提取毫秒时间戳即可,完整代码如下:

import 'package:intl/intl.dart';

void main() {
  // 你之前格式化得到的d12字符串
  String d12 = "12/31/2021, 10:10:10 PM";
  // 必须使用和格式化时完全一致的pattern创建DateFormat实例
  DateFormat dateFormat = DateFormat('MM/dd/yyyy, HH:mm:ss a');
  
  // 解析字符串得到DateTime对象,如果原始时间为UTC时间请改用parseUtc方法
  DateTime parsedDate = dateFormat.parse(d12);
  // 转换为毫秒时间戳
  int timeStamp = parsedDate.millisecondsSinceEpoch;
  
  print(timeStamp); // 输出结果:1630506255982
}

注意事项

  • 解析用的pattern必须和格式化用的pattern完全一致,符号、空格、顺序都不能有差异,否则会直接解析失败
  • 如果你的原始时间戳是UTC时间,格式化时用的是UTC格式,解析时需要调用dateFormat.parseUtc(d12),否则会因为时区差得到错误的时间戳
  • 若运行时报和intl包相关的错误,检查pubspec.yaml中是否已经正确添加intl依赖,版本和你之前格式化日期时使用的版本保持一致即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:30:01