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

Flutter(Dart)中如何将Date(1639580400000-0000)转为指定日期格式

Flutter Dart日期格式转换方案

要把Date(1639580400000-0000)这种格式的字符串转成exp- (12-MAY-2023)样式,核心是提取时间戳、转成DateTime对象再格式化,具体步骤如下:

1. 提取时间戳

从输入字符串里剥离出毫秒级时间戳,用正则表达式最方便:

String startDateTime = "Date(1639580400000-0000)";
// 匹配字符串里的数字部分
final timestampMatch = RegExp(r'\d+').firstMatch(startDateTime);
if (timestampMatch == null) {
  // 处理格式错误的情况
  print("无效的日期格式");
  return;
}
final timestamp = int.parse(timestampMatch.group(0)!);

2. 生成DateTime对象

输入里的-0000表示UTC时区,直接用毫秒时间戳创建UTC时间:

final dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp, isUtc: true);

3. 格式化目标字符串

需要用到官方的intl包来处理日期格式化,先在pubspec.yaml添加依赖:

dependencies:
  intl: ^0.18.1 # 可用最新版本

执行flutter pub get安装后,导入包并格式化:

import 'package:intl/intl.dart';

// 指定格式为dd-MMM-yyyy,用en_US确保月份缩写是英文
final formatted = DateFormat('dd-MMM-yyyy', 'en_US').format(dateTime).toUpperCase();
final result = 'exp- ($formatted)';
// result就是 exp- (12-MAY-2023) 样式的字符串

完整可运行代码

import 'package:intl/intl.dart';

void main() {
  const startDateTime = "Date(1639580400000-0000)";
  
  final timestampMatch = RegExp(r'\d+').firstMatch(startDateTime);
  if (timestampMatch == null) {
    print("无效的日期格式");
    return;
  }
  
  final timestamp = int.parse(timestampMatch.group(0)!);
  final dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp, isUtc: true);
  
  final formattedDate = DateFormat('dd-MMM-yyyy', 'en_US').format(dateTime).toUpperCase();
  final result = 'exp- ($formattedDate)';
  
  print(result);
}

注意点

  • 必须确保intl包安装成功,否则无法使用DateFormat
  • 如果输入的时区不是UTC,需要额外解析时区偏移量来创建正确的DateTime对象
  • 指定en_US locale是为了避免系统语言影响月份缩写的显示,保证输出是英文大写的月份缩写

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:10:14