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

Flutter如何从日期时间字符串提取时分?正则尝试未成功

在Flutter中提取日期时间字符串的小时和分钟

以下是几种可靠的实现方式,解决你提取hh:mm格式时间的需求:

方法一:使用DateTime类解析(推荐)

这种方式最稳妥,能自动处理日期时间格式的合法性,还能避免正则或字符串分割在格式变动时出错:

String? time = "2023-02-21 14:50:40";
if (time != null) {
  DateTime dateTime = DateTime.parse(time);
  // 用padLeft确保小时/分钟是两位数(比如9点转为"09")
  String hourMinute = "${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}";
  print(hourMinute); // 输出 "14:50"
}

方法二:正则表达式(修正你之前的尝试)

如果坚持用正则,需要精准定位空格后的小时分钟部分,以下是可行的写法:

String? time = "2023-02-21 14:50:40";
if (time != null) {
  // 匹配空格后两位数字+冒号+两位数字的组合
  RegExp regExp = RegExp(r'\s(\d{2}:\d{2})');
  Match? match = regExp.firstMatch(time);
  if (match != null) {
    String hourMinute = match.group(1)!;
    print(hourMinute); // 输出 "14:50"
  }
}

方法三:字符串分割(适合固定格式场景)

如果你的日期时间格式永远是yyyy-MM-dd hh:mm:ss,可以直接分割字符串提取:

String? time = "2023-02-21 14:50:40";
if (time != null) {
  List<String> parts = time.split(' ');
  if (parts.length > 1) {
    // 取时间部分的前5个字符
    String hourMinute = parts[1].substring(0, 5);
    print(hourMinute); // 输出 "14:50"
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 00:21:26