LocalDateTime:将字符串转换为HH:mm:ss [英] LocalDateTime : converting String to HH:mm:ss

查看:1007
本文介绍了LocalDateTime:将字符串转换为HH:mm:ss的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做什么:

我需要将LocalDateTime对象传递给构造函数,并且我有一个字符串,其值为 18:14:00。

What I need to do :
I need to pass a LocalDateTime object to a constructor and I have a string that have "18:14:00" as value.

我的问题:

如何将字符串转换为LocalDateTime?

My question :
How can I convert the string to LocalDateTime ?

我做了什么:

经过一些研究,我把它放了出来,但是没用:

What I have done :
After some researches, I put this but it didn't work :

LocalDateTime.parse("18:14:00", DateTimeFormatter.ofPattern("HH:mm:ss"));




java.time.format.DateTimeParseException:文本'18:14: 00'无法被
解析:无法从TemporalAccessor中获取LocalDateTime:{},ISO
解析为java.time.format.Parsed类型的18:14

java.time.format.DateTimeParseException: Text '18:14:00' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 18:14 of type java.time.format.Parsed


推荐答案

无法获取LocalDateTime 异常是因为解析的文本仅具有 time 值,没有 date 值,因此无法构造Local Date 时间对象。

The "Unable to obtain LocalDateTime" exception is because the parsed text only has time values, no date values, so it is impossible to construct a Local​Date​Time object.

解析为 LocalTime 代替:

Parse to a LocalTime instead:

LocalTime time = LocalTime.parse("18:14:00");

System.out.println(dateTime); // Prints: 18:14

HH:mm:ss 模式是 LocalTime 的默认模式,因此无需指定它(请参阅: DateTimeFormatter.ISO_LOCAL_TIME )。

The "HH:mm:ss" pattern is the default for a LocalTime, so there is no need to specify it (see: DateTimeFormatter.ISO_LOCAL_TIME).

如果您想要/需要 LocalDateTime 对象,其解析类似于 SimpleDateFormat 做到了,即默认为1970年1月1日,那么您需要明确指定默认日期值:

If you want/need a LocalDateTime object, parsed similarly to how SimpleDateFormat did it, i.e. defaulting the Jan 1, 1970, then you need to explicitly specify the default date value:

DateTimeFormatter fmt = new DateTimeFormatterBuilder()
        .append(DateTimeFormatter.ISO_LOCAL_TIME)
        .parseDefaulting(ChronoField.EPOCH_DAY, 0)
        .toFormatter();
LocalDateTime dateTime = LocalDateTime.parse("18:14:00", fmt);

System.out.println(dateTime); // Prints: 1970-01-01T18:14

为进行比较,它相当于旧的 SimpleDateFormat 结果:

For comparison, that is equivalent to the old SimpleDateFormat result:

Date date = new SimpleDateFormat("HH:mm:ss").parse("18:14:00");

System.out.println(date); // Prints: Thu Jan 01 18:14:00 EST 1970

这篇关于LocalDateTime:将字符串转换为HH:mm:ss的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆