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

Flutter中如何从‘2024-07-22 04:55:00.000+0230’提取时分时间

Flutter 提取时间字符串中的时分部分

针对时间字符串 '2024-07-22 04:55:00.000+0230',可以用两种实用方法提取时分:

方法一:直接字符串截取

原字符串的时分部分固定在空格后的前5位,可通过字符串索引直接截取:

String fullTime = '2024-07-22 04:55:00.000+0230';
// 截取带前导零的时分 '04:55'
String hourMinuteWithZero = fullTime.substring(fullTime.indexOf(' ') + 1, fullTime.indexOf(' ') + 6);
print(hourMinuteWithZero); // 输出 04:55

// 处理为不带前导零的格式 '4:55'
List<String> parts = hourMinuteWithZero.split(':');
String hour = int.parse(parts[0]).toString();
String hourMinuteWithoutZero = '$hour:${parts[1]}';
print(hourMinuteWithoutZero); // 输出 4:55

方法二:通过 DateTime 解析格式化(更规范)

利用Flutter内置的DateTime类解析完整时间,再按需格式化时分,适配更多时间格式变化:

import 'package:intl/intl.dart';

String fullTime = '2024-07-22 04:55:00.000+0230';
DateTime dateTime = DateTime.parse(fullTime);

// 输出带前导零的时分 '04:55'
String formattedWithZero = DateFormat('HH:mm').format(dateTime);
print(formattedWithZero);

// 输出不带前导零的时分 '4:55'
String formattedWithoutZero = DateFormat('h:mm').format(dateTime);
print(formattedWithoutZero);

注意:使用intl包需在pubspec.yaml中添加依赖:

dependencies:
  intl: ^0.18.1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:25:56