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

191,290

Solution 1

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

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

Solution 2

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:

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

Solution 3

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

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.

Edit : usefull thing from wittyameta comment :

Remember to add the parseDefaulting AFTER you have called appendPattern. Otherwise it'll give DateTimeParseException

Solution 4

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

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.

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

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

Solution 5

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

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

Share:
191,290

Related videos on Youtube

retrography
Author by

retrography

Updated on July 08, 2022

Comments

  • retrography
    retrography almost 2 years

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

    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.

    • Salvatore Pannozzo Capodiferro
      Salvatore Pannozzo Capodiferro over 3 years
      why are you using LocalDateTime without a time?
  • Hakanai
    Hakanai over 8 years
    Correction: set to whatever time it would be at the start of that day.
  • Dariusz
    Dariusz over 8 years
    LocalDateTime.from seems unnecessary, as atStartOfDay() already returns LocalDateTime.
  • ZeroOne
    ZeroOne over 8 years
    For what it's worth: I had this same problem even when using LocalDate and not LocalDateTime. The issue was that I had created my DateTimeFormatter using .withResolverStyle(ResolverStyle.STRICT);, so I had to use date pattern uuuuMMdd instead of yyyyMMdd (i.e. "year" instead of "year-of-era")!
  • toootooo
    toootooo about 7 years
    This is true universal solution for instance for such method: Long getFileTimestamp(String file, Pattern pattern, DateTimeFormatter dtf, int group); Here you have different patterns and DateTimeFormetter, w/ and w/o time specified.
  • Woody Sun
    Woody Sun over 6 years
    scala: val time = LocalDate.parse("20171220", DateTimeFormatter.ofPattern("yyyyMMdd")).atStartOfDay.format‌​(DateTimeFormatter.o‌​fPattern("yyyy-MM-dd HH:mm:ss"))
  • Kamil Roman
    Kamil Roman over 6 years
    Can it be a static field? I have not found in the Javadoc that an instance created that way is thread-safe
  • wittyameta
    wittyameta over 5 years
    Remember to add the parseDefaulting AFTER you have called appendPattern. Otherwise it'll give DateTimeParseException.
  • patstuart
    patstuart about 5 years
    Also make sure the format is correct. This fix didn't work for me until because I set the format to yyyy-mm-dd when it should have been yyyy-MM-dd.
  • prashanth
    prashanth over 4 years
    The answer to why "u" instead of "y"has been answered in this link uuuu-versus-yyyy-in-datetimeformatter-formatting-pattern-cod‌​es-in-java @Peru
  • Panagiss
    Panagiss over 3 years
    when using HH for hours in the pattern, i get 00 for AM hours
  • gourabix
    gourabix over 3 years
    @ZeroOne's comment should be included as part of the selected answer.
  • ZeroOne
    ZeroOne over 3 years
    @gourabix I've posted my comment as a separate answer, you may upvote that one. Eventually it will surpass the accepted one in the number of votes...
  • cmorris
    cmorris about 3 years
    @iulian-david 's answer was more helpful here and actually solved the problem of parsing a datetime that may or may not have a time part.
  • Nano
    Nano over 2 years
    "Java does not accept a bare Date value as DateTime"! What a rediculous feature!
  • Walfrat
    Walfrat over 2 years
    For those who don't want to convert to localeDate see Julian David answer