0

I have this strange situation. Following code

LocalDateTime.parse(
    LocalDateTime.now().format(DateTimeFormatter.ISO_DATE),
    DateTimeFormatter.ISO_DATE
);

throws

java.time.format.DateTimeParseException: Text '2018-07-05' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2018-07-05 of type java.time.format.Parsed

It looks like it cannot parse it's own formatted date.

openjdk version "1.8.0_141" OpenJDK Runtime Environment (build 1.8.0_141-8u141-b15-3~14.04-b15) OpenJDK 64-Bit Server VM (build 25.141-b15, mixed mode)

CodeMatrix
  • 2,124
  • 1
  • 18
  • 30
rattaman
  • 506
  • 3
  • 15
  • 1
    When your format your date-time into a date string only, information is lost. Therefore there is not enough information to parse a date-time back: the date is there, the time is missing. This causes the exception. – Ole V.V. Jul 05 '18 at 17:50
  • Reasonable assumption would be 00:00 and I think anyone using this code in such a manner would expect such behavior. I would say this is a limitation of implementation rather than of the idea itself. – rattaman Jul 06 '18 at 11:07
  • Assumption is the mother of all (not so nice word omitted). You need not agree, but for my part I consider it a strength of `java.time` that it often forces you to make your reasonable assumptions explicit in your code. For example: `LocalDate.parse(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE), DateTimeFormatter.ISO_DATE).atStartOfDay()`. It’s very few chars longer, and it much more clearly and unambiguously conveys the intention. – Ole V.V. Jul 06 '18 at 11:12
  • In general I agree, that assumptions can be dangerous. That being said, this is a quite intuitive subject as we are talking about dates and plenty of date related tools behave in this way. This expectation is rather intuitive, if you don't provide other values, they are zeros. Even javadoc for ISO_DATE says it's used to format dates and times, so if you read the docs, you can expect for this to work, especially that it is DateTimeFormatter, and not for example DateFormatter. – rattaman Jul 06 '18 at 11:24
  • Detail, [“The ISO date formatter that formats or parses a date with the offset if available, such as '2011-12-03' or '2011-12-03+01:00'.”](https://docs.oracle.com/javase/9/docs/api/java/time/format/DateTimeFormatter.html#ISO_DATE) I see nothing about formatting times in the Javadoc for this particular formatter. – Ole V.V. Jul 06 '18 at 11:42
  • It's called DateTimeFormatter (so it suggests it works for DateTime) and then it says "formatter that formats or parses a date" and indeed you can use it with DateTime, but not for parsing, just for formatting. So either it shouldn't work in any way (if it's only for dates) or work both ways. – rattaman Jul 06 '18 at 11:49
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/174495/discussion-between-ole-v-v-and-rattaman). – Ole V.V. Jul 06 '18 at 11:54

0 Answers0