微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 的更多信息。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。