【问题标题】:java.time.format.DateTimeParseException: Text '21:5:20' could not be parsed at index 3java.time.format.DateTimeParseException:无法在索引 3 处解析文本“21:5:20”
【发布时间】:2021-09-10 05:58:36
【问题描述】:

我目前收到此错误,我真的不知道为什么

java.time.format.DateTimeParseException: Text '21:5:20' could not be parsed at index 3
        at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
        at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
        at java.time.LocalTime.parse(LocalTime.java:441)
...

这是我用来解析的方法。

public static ZonedDateTime parse(String fecha, String pattern) {
    DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME;
    LocalTime date = LocalTime.parse(fecha, formatter);

    return ZonedDateTime.of(LocalDateTime.of(LocalDate.now(), date), ZoneId.systemDefault());
  }

我需要返回ZonedDateTime,因此我正在做我正在做的事情。 错误说它似乎从文件21:5:20 中读取了正确的时间,这看起来是有效的,但由于某种原因它无法解析它。

我真的不知道我做错了什么。与此类似的问题是指日期,而不是时间。

我知道这似乎是一个微不足道的问题,但我真诚地感谢 Java 专家的帮助。提前谢谢你。

【问题讨论】:

  • 确保时间字符串中的所有时间元素都包含 2 位数字(如分钟中缺少的前导 0)。
  • @DevilsHnd 我无法更改输入,呵呵。数据是从某处读取的。

标签: java localtime zoneddatetime localdatetime


【解决方案1】:

ISO_LOCAL_TIME 的时间格式不正确。 小时、分钟和秒的宽度分别为 2 位数字。 它们应该用零填充以确保两位数。 可解析的时间是:21:05:20

如果无法更改输入格式,可以创建自己的 DateTimeFormatter:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendValue(HOUR_OF_DAY, 2)
        .appendLiteral(':')
        .appendValue(MINUTE_OF_HOUR, 1, 2, SignStyle.NEVER)
        .optionalStart()
        .appendLiteral(':')
        .appendValue(SECOND_OF_MINUTE, 2)
        .toFormatter();

LocalTime date = LocalTime.parse("21:5:20", formatter);

System.out.println(date);

打印:

21:05:20

【讨论】:

  • 好吧,我无法更改输入,有什么办法可以解析这种时间格式吗?
  • 句柄是什么意思?顺便说一句,我想在方法本身内部将字符串拆分为:,然后执行`LocalTime date = LocalTime.of(Integer.parseInt(s[0]), Integer.parseInt(s[1]), Integer。 parseInt(s[2]));`.现在解锁了一个全新的错误世界。
【解决方案2】:

使用格式"H:m:s"

详情:

DateTimeFormatter.ISO_LOCAL_TIME 中的小时、分钟和秒的格式为 HH:mm:ss,而您的时间字符串没有两位数的分钟。 "H:m:s" 格式适用于单位数和两位数的时间单位。

演示:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {

    public static void main(String[] args) {
        System.out.println(parse("21:5:20", "H:m:s"));
    }

    public static ZonedDateTime parse(String fecha, String pattern) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH);
        LocalTime time = LocalTime.parse(fecha, formatter);

        return ZonedDateTime.of(LocalDateTime.of(LocalDate.now(), time), ZoneId.systemDefault());
    }

}

在我的时区输出:

2021-06-27T21:05:20+01:00[Europe/London]

ONLINE DEMO

Trail: Date Time 了解有关现代日期时间 API 的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2020-06-25
    相关资源
    最近更新 更多