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

Flutter中如何移除文本末尾的三位数字?

移除DateTime字符串末尾三位数字的解决方案

你的代码直接将DateTime转为字符串后会包含毫秒部分(格式类似2024-05-20 14:30:45.123),以下两种方法可以移除末尾的三位数字:

方法1:字符串截取

直接截取字符串到毫秒部分之前,去掉最后的.xxx:

DataCell(Text(
  DateTime.parse(e['start'].toString()).toLocal().toString().substring(0, DateTime.parse(e['start'].toString()).toLocal().toString().length - 4)
)),

或者先把时间对象存起来,让代码更简洁:

final localTime = DateTime.parse(e['start'].toString()).toLocal();
DataCell(Text(localTime.toString().substring(0, localTime.toString().length - 4))),

方法2:使用DateFormat格式化(推荐)

这种方法更规范,避免直接操作字符串,需要先引入intl包:

  1. 在pubspec.yaml中添加依赖:
dependencies:
  intl: ^0.19.0
  1. 在代码中导入并使用:
import 'package:intl/intl.dart';

// ...

DataCell(Text(
  DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.parse(e['start'].toString()).toLocal())
)),

通过指定日期格式,自动忽略毫秒部分,同时还能自定义显示的日期时间样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:50:20