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

问题描述

我有以下字符串:

18/07/2019 16:20

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

val stringDate = expire_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时间访问器

我缺少什么?

解决方案

我想这会回答你的问题:

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

编辑 1:

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

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

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

I have the following String:

18/07/2019 16:20

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()

What I'm missing?

解决方案

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);

Edit 1:

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 10:04