java - LocalDate 的特殊字符串
问题描述
从以下字符串中,我想获取 LocalDate 或 LocalDateTime。
2019 年 1 月 1 日 12:00:00
我已经尝试了以下代码,但出现以下错误:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d, yyyy hh:mm:ss a"); // also with dd
formatter = formatter.withLocale(Locale.GERMAN);
LocalDateTime localDateTime = LocalDateTime.parse(stringDate, formatter);
LocalDate localDate = LocalDate.parse(stringDate, formatter);
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Jan 1, 2019 12:00:00 AM' could not be parsed at index 0
最后,我希望约会的方式就像
- 2019 年 1 月 1 日。本地日期
- 2019 年 1 月 1 日。12:00 本地日期时间(24 小时)
这甚至可能吗?相反,使用正则表达式会不会过大?
解决方案
您的代码存在一些问题,但我将在这里提出一个可行的解决方案:
HH
是一天中的小时,而不是 0-12 小时(即hh
)- 你应该使用 DateTimeFormatterBuilder
- 您应该使用正确的语言环境,可能
GERMANY
而不是GERMAN
- 月份的名称表示为
L
,而不是M
- 德语语言环境使用
vorm.
andnachm.
而不是AM
andPM
-> 一个快速的解决方案是替换术语
把它们放在一起给我们留下了这个:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
class Scratch {
public static void main(String[] args) {
String stringDate = "Jan 1, 2019 11:00:00 PM";
stringDate = stringDate.replace("AM", "vorm.");
stringDate = stringDate.replace("PM", "nachm.");
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("LLL d, yyyy hh:mm:ss a")
.toFormatter(Locale.GERMANY);
LocalDateTime localDateTime = LocalDateTime.parse(stringDate, formatter);
LocalDate localDate = LocalDate.parse(stringDate, formatter);
}
}
如果有人有不同的方法来处理AM
/ vorm.
-dilemma,我会很高兴看到它!