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

如何让LocalDateTime.parse拒绝24:00格式的时间输入

问题:LocalDateTime解析24:00时间未抛出异常反而转换为次日时间

我有一个允许用户通过键盘输入日期时间的表单,目前发现LocalDateTime会接受时间部分为24:00的输入,并将其自动转换为次日的00:00时间,这不符合预期。

我的代码如下:

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

val INPUT_DATETIME_PATTERN = "yyyyMMddHHmm"
val formatter = DateTimeFormatter.ofPattern(INPUT_DATETIME_PATTERN)
    
val datetime = "202308102400"

val localdatetime = LocalDateTime.parse(datetime, formatter)
println(datetime)
println(localdatetime.format(formatter))
  • 预期结果:LocalDateTime.parse()应该抛出异常。根据官方文档定义,HH代表一天中的小时(范围0-23),因此2400属于无效格式,输入202308102401这类值时也应该抛出异常。
  • 实际结果:程序输出202308102400和202308110000,即输入的202308102400被自动转换为了次日的00:00。该结果已在Android Studio临时文件和Kotlin playground中验证。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 01:37:19