java.time.format.DateTimeParseException: 无法在索引 3 处解析文本“21:5:20”

问题描述

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

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 专家的帮助。提前致谢。

解决方法

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

,

TL;DR

使用格式 "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 了解有关现代 Date-Time API 的更多信息。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...