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

Java 8中如何解析14h、17h30这类自定义时间格式?

解决自定义时间字符串解析问题

要同时解析14h和17h30这类格式的时间字符串,不需要通过catch块逐个尝试模式,Java时间API可以直接支持多格式匹配,核心思路是利用可选格式分量:

方法1:使用带可选部分的模式字符串

直接在格式模式中用方括号[]标记可选的时间部分,这样一个DateTimeFormatter就能兼容两种格式:

// 方括号表示mm部分是可选的
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("k'h'[mm]");

// 测试两种格式
LocalTime time1 = LocalTime.parse("14h", formatter); // 解析为14:00
LocalTime time2 = LocalTime.parse("17h30", formatter); // 解析为17:30

方法2:使用DateTimeFormatterBuilder构建(适合复杂场景)

如果需要更灵活的格式组合,可以用DateTimeFormatterBuilder的optionalStart()和optionalEnd()方法显式定义可选段:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("k'h'") // 必选的小时部分
        .optionalStart() // 开始定义可选段
        .appendPattern("mm") // 可选的分钟部分
        .optionalEnd()
        .toFormatter();

// 同样支持两种格式解析
LocalTime time1 = LocalTime.parse("14h", formatter);
LocalTime time2 = LocalTime.parse("17h30", formatter);

为什么之前的代码会报错?

你之前的问题在于单个模式只能严格匹配一种格式:

  • 用k'h'm时,要求字符串必须包含小时、h、分钟三个部分,14h缺少分钟,所以抛出DateTimeParseException
  • 用k'h'时,字符串只能有小时和h,14h30多了分钟部分,同样不符合匹配规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:15:31