Flutter中如何使用DateFormat将String类型日期转为MM-dd-yyyy美制日期格式
Flutter 日期转MM-dd-yyyy美制格式解决方案
首先确认你的pubspec.yaml文件已引入intl依赖:
dependencies: flutter: sdk: flutter intl: ^0.18.1 # 可替换为当前最新稳定版本
分场景处理方案
场景1:createdAt返回值为DateTime类型
直接调用DateFormat的format方法传入DateTime对象即可,注意月份的格式符为大写MM,小写mm对应分钟,不要写混:
import 'package:intl/intl.dart'; // 你的组件代码 alignment: Alignment.topLeft, child: Text( DateFormat('MM-dd-yyyy').format( sl<IIndividualDataProvider>().reads[index].createdAt ), ),
场景2:createdAt返回值为标准格式的日期字符串(如ISO8601格式)
先将字符串解析为DateTime对象,再做格式化:
alignment: Alignment.topLeft, child: Text( DateFormat('MM-dd-yyyy').format( DateTime.parse(sl<IIndividualDataProvider>().reads[index].createdAt) ), ),
场景3:createdAt返回值为非标准格式的日期字符串
先按照原始日期的格式解析为DateTime对象,再转换为目标格式,例如原始日期为日/月/年格式的字符串:
alignment: Alignment.topLeft, child: Text( DateFormat('MM-dd-yyyy').format( DateFormat('dd/MM/yyyy').parse(sl<IIndividualDataProvider>().reads[index].createdAt) ), ),
常见问题排查
- 若编译提示DateFormat类不存在,执行
flutter pub get后重新编译项目 - 若格式化后月份显示为00-59的数字,检查是否误将
MM写为小写mm - 若需要严格适配美式显示规则,可给DateFormat指定locale参数:
DateFormat('MM-dd-yyyy', 'en_US')
内容的提问来源于stack exchange,提问作者Boon
相关产品推荐
相关产品推荐

