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

DateFormat.parse解析正常格式时间字符串失败问题求助

字符串转TimeOfDay抛出FormatException的解决方法

问题原因

你使用的DateFormat.jm()要求输入字符串必须包含AM/PM标识(如"6:00 AM"),但测试的部分输入(如"6:00"、"16:00")不符合该格式;同时24小时制的输入需要对应24小时制的DateFormat格式符,否则会解析失败。

解决方案

根据输入字符串的格式,选择匹配的DateFormat:

  • 24小时制无秒(如"16:00"):使用DateFormat.Hm()
  • 24小时制带秒(如"16:00:00"):使用DateFormat.Hms()
  • 12小时制带AM/PM(如"6:00 AM"):使用DateFormat.jm()
  • 12小时制带秒和AM/PM(如"6:00:00 AM"):使用DateFormat.jms()

示例代码

处理24小时制无秒输入

try {
    final format = DateFormat.Hm();
    TimeOfDay day = TimeOfDay.fromDateTime(format.parse("16:00"));
} catch(ex) {
    PLPrint(name: "CheckTest", value: "${ex.toString()}");
}

处理12小时制带AM/PM输入

try {
    final format = DateFormat.jm();
    TimeOfDay day = TimeOfDay.fromDateTime(format.parse("6:00 AM"));
} catch(ex) {
    PLPrint(name: "CheckTest", value: "${ex.toString()}");
}

处理带秒的24小时制输入

try {
    final format = DateFormat.Hms();
    TimeOfDay day = TimeOfDay.fromDateTime(format.parse("16:00:00"));
} catch(ex) {
    PLPrint(name: "CheckTest", value: "${ex.toString()}");
}

额外排查点

如果此前功能正常现在失效,检查:

  • intl包是否有版本更新,回退到之前的稳定版本测试
  • 应用的区域设置是否被修改,可显式指定区域确保解析一致,比如DateFormat.jm('en_US')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 19:16:06