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
相关产品推荐
相关产品推荐

