解析 LocalDateTime (Java 8) 时无法从 TemporalAccessor 获取 LocalDateTime

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27454025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:23:56  来源:igfitidea点击:

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

javadatetimejava-8datetime-format

提问by retrography

I am simply trying to convert a date string into a DateTime object in Java 8. Upon running the following lines:

我只是想在 Java 8 中将日期字符串转换为 DateTime 对象。运行以下几行后:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime dt = LocalDateTime.parse("20140218", formatter);

I get the following error:

我收到以下错误:

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)

The syntax is identical to what has been suggested here, yet I am served with an exception. I am using JDK-8u25.

语法与此处建议的相同,但我有一个例外。我正在使用JDK-8u25.

采纳答案by retrography

It turns out Java does not accept a bare Date value as DateTime. Using LocalDate instead of LocalDateTime solves the issue:

事实证明,Java 不接受一个裸 Date 值作为 DateTime。使用 LocalDate 而不是 LocalDateTime 解决了这个问题:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate dt = LocalDate.parse("20140218", formatter);

回答by Tom B

This is a really unclear and unhelpful error message. After much trial and error I found that LocalDateTimewill give the above error if you do not attempt to parse a time. By using LocalDateinstead, it works without erroring.

这是一个非常不清楚和无用的错误消息。经过多次反复试验,我发现LocalDateTime如果您不尝试解析时间,则会出现上述错误。通过使用LocalDate,它可以正常工作而不会出错。

This is poorly documented and the related exception is very unhelpful.

这没有很好的记录,相关的异常也非常无用。

回答by ?yvind Mo

If you really need to transform a date to a LocalDateTime object, you could use the LocalDate.atStartOfDay(). This will give you a LocalDateTime object at the specified date, having the hour, minute and second fields set to 0:

如果您确实需要将日期转换为 LocalDateTime 对象,则可以使用 LocalDate.atStartOfDay()。这将在指定日期为您提供一个 LocalDateTime 对象,将小时、分钟和秒字段设置为 0:

final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime time = LocalDate.parse("20140218", formatter).atStartOfDay();

回答by Iulian David

For what is worth if anyone should read again this topic(like me) the correct answer would be in DateTimeFormatterdefinition, e.g.:

如果有人应该再次阅读这个主题(像我一样),正确的答案应该是在DateTimeFormatter定义中,例如:

private static DateTimeFormatter DATE_FORMAT =  
            new DateTimeFormatterBuilder().appendPattern("dd/MM/yyyy[ [HH][:mm][:ss][.SSS]]")
            .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
            .toFormatter(); 

One should set the optional fields if they will appear. And the rest of code should be exactly the same.

如果出现可选字段,则应设置它们。其余代码应该完全相同。

回答by ZeroOne

Expanding on retrography's answer..: I had this same problem even when using LocalDateand not LocalDateTime. The issue was that I had created my DateTimeFormatterusing .withResolverStyle(ResolverStyle.STRICT);, so I had to use date pattern uuuuMMddinstead of yyyyMMdd(i.e. "year" instead of "year-of-era")!

扩展retrography的答案..:即使在使用LocalDate和不使用时,我也遇到了同样的问题LocalDateTime。问题是我创建了DateTimeFormatterusing .withResolverStyle(ResolverStyle.STRICT);,所以我必须使用日期模式uuuuMMdd而不是yyyyMMdd(即“年份”而不是“年代”)!

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
  .parseStrict()
  .appendPattern("uuuuMMdd")
  .toFormatter()
  .withResolverStyle(ResolverStyle.STRICT);
LocalDate dt = LocalDate.parse("20140218", formatter);

(This solution was originally a comment to retrography's answer, but I was encouraged to post it as a stand-alone answer because it apparently works really well for many people.)

(这个解决方案最初是对逆转录的答案的评论,但我被鼓励将其作为独立的答案发布,因为它显然对许多人来说非常有效。)

回答by prime

If the date String does not include any value for hours, minutes and etc you cannot directly convert this to a LocalDateTime. You can only convert it to a LocalDate, because the string onlyrepresentthe year,month and datecomponents it would be the correct thing to do.

如果日期字符串不包含小时、分钟等的任何值,则不能直接将其转换为LocalDateTime. 您只能将其转换为一个LocalDate,因为字符串代表年份,月份和日期组件它是做正确的事。

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf); // 2018-03-06

Anyway you can convert this to LocalDateTime.

无论如何,您可以将其转换为LocalDateTime.

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf);
LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(0,0)); // 2018-03-06T00:00

回答by mawburn

For anyone who landed here with this error, like I did:

对于遇到此错误的任何人,就像我一样:

Unable to obtain LocalDateTime from TemporalAccessor: {HourOfAmPm=0, MinuteOfHour=0}

Unable to obtain LocalDateTime from TemporalAccessor: {HourOfAmPm=0, MinuteOfHour=0}

It came from a the following line:

它来自以下行:

LocalDateTime.parse(date, DateTimeFormatter.ofPattern("M/d/yy h:mm"));

It turned out that it was because I was using a 12hr Hour pattern on a 0 hour, instead of a 24hr pattern.

原来这是因为我在 0 小时使用了 12 小时模式,而不是 24 小时模式。

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

使用大写 H 将小时更改为 24 小时模式修复它:

LocalDateTime.parse(date, DateTimeFormatter.ofPattern("M/d/yy H:mm"));

回答by Vinay Kasarla

Try this one:

试试这个:

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy"); 
LocalDate fromLocalDate = LocalDate.parse(fromdstrong textate, dateTimeFormatter);

You can add any format you want. That works for me!

您可以添加任何您想要的格式。这对我行得通!

回答by Jeff Cook

This works fine

这工作正常

public class DateDemo {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm");
        String date = "16-08-2018 12:10";
        LocalDate localDate = LocalDate.parse(date, formatter);
        System.out.println("VALUE="+localDate);

        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
        LocalDateTime parse = LocalDateTime.parse(date, formatter1);
        System.out.println("VALUE1="+parse);
    }
}

output:

输出:

VALUE=2018-08-16
VALUE1=2018-08-16T12:10