将字符串转换为LocalDateTime [英] Convert string into LocalDateTime

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

问题描述

我有以下字符串:

18/07/2019 16:20

我尝试使用以下代码将此字符串转换为LocalDateTime:

I try to convert this string into LocalDateTime with the following code:

val stringDate = expiration_button.text.toString()
val date = LocalDateTime.parse(stringDate, DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm")).toString()

java.time.format.DateTimeParseException:文本'18/07/2019 04:30:00' 无法解析:无法从中获取LocalDateTime TemporalAccessor

java.time.format.DateTimeParseException: Text '18/07/2019 04:30:00' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor

我缺少什么?

推荐答案

我认为这将回答您的问题:

I think this will answer your question:

val stringDate = expiration_button.text.toString()
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm");
val dt = LocalDate.parse(stringDate, formatter);

由于您使用的是12小时制而不是24小时制,因此可能会崩溃.

It's probably crashing because you are using a 12hr Hour, instead of a 24hr pattern.

使用大写字母H将小时更改为24小时应该可以解决此问题:

Changing the hour to 24hr pattern by using a capital H should fix it:

val dateTime = LocalDateTime.parse(stringDate, DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"));

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

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