我只是想在Java 8中将日期字符串转换为DateTime对象.运行以下行:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime dt = LocalDateTime.parse("20140218", formatter);
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Exception in thread "main" java.time.format.DateTimeParseException:
Text '20140218' could not be parsed:
Unable to obtain LocalDateTime from TemporalAccessor:
{},ISO resolved to 2014-02-18 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
Run Code Online (Sandbox Code Playgroud)
语法与此处的建议相同,但我遇到了一个例外.我在用JDK-8u25.
我需要解析一个有时作为日期而有时作为日期/时间的字段.是否可以使用Java 8时间API为此使用单一数据类型?目前,我尝试使用LocalDateTime,但是对于以下调用,LocalDateTime.parse("1986-04-08", DateTimeFormatter.ofPattern("yyyy-MM-dd"))
我得到了一个
java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 1986-04-08 of type java.time.format.Parsed
Run Code Online (Sandbox Code Playgroud)
这是一些通用解析器的一部分,它接受日期/日期时间解析模式作为配置选项.因此,例如遵循具有硬编码解析模式的解决方案
if ("yyyy-MM-dd".equals(pattern)) {
LocalDate.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd"))).atStartOfDay()
}
Run Code Online (Sandbox Code Playgroud)
对我来说不是一个选择.
任何其他建议如何以干净的方式编码它是受欢迎的.
在以下代码中:
ZonedDateTime zdt = ZonedDateTime.now();
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String zdtString = FORMATTER.format(zdt);
System.out.println(zdtString);
Run Code Online (Sandbox Code Playgroud)
您将看到它以 yyyy-DD-mm 格式打印出当前日期。由于这个问题是在 2021 年 7 月 17 日发布的,所以它打印了:
2021-07-17
Run Code Online (Sandbox Code Playgroud)
但是现在我想将日期更改为不同的日期(例如 1994-03-24)。
所以我试过:
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZonedDateTime zdt2 = ZonedDateTime.parse("1994-03-24", FORMATTER);
String zdtString = FORMATTER.format(zdt2);
System.out.println(zdtString);
Run Code Online (Sandbox Code Playgroud)
但后来我得到以下异常:
Exception in thread "main" java.time.format.DateTimeParseException: Text '1994-03-24' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 1994-03-24 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)
at javaapplication5.JavaApplication5.main(JavaApplication5.java:48)
Caused by: java.time.DateTimeException: Unable to obtain …Run Code Online (Sandbox Code Playgroud)