0

I am trying to use Java's DateTimeFormatter to convert LocalDateTime to/from a formatted String.

The format I want is specified in Common Log Format.

So, to use that format, I define an instance of DateTimeFormatter with the appropriate pattern, then I try to use it like this (written in Groovy, but results are the same in Java):

import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalQueries

def formatter = DateTimeFormatter
        .ofPattern("d/MMM/Y:HH:mm:ss z")
        .withLocale(Locale.getDefault())
        .withZone(ZoneId.systemDefault())

def now = LocalDateTime.now()
def text = now.format(formatter)
println "Text: $text"

def parsedDateTime = LocalDateTime.parse(text, formatter)
println "Parsed: $parsedDateTime"
assert parsedDateTime == now

This prints the text correctly:

Text: 17/Mar/2018:21:22:26 CET

But on the third last line in the code above, when trying to parse this text back, an error occurs:

java.time.format.DateTimeParseException: Text '17/Mar/2018:21:22:26 CET'
could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: 
{MonthOfYear=3, DayOfMonth=17,WeekBasedYear[WeekFields[SUNDAY,1]]=2018},ISO,Europe/Paris
resolved to 21:22:26 of type java.time.format.Parsed

I also tried using formatter.parse(text) instead of LocalDateTime.parse(text, formatter) and it does parse successfully!! But then, the return type is TemporalAccessor and I do really need a LocalDateTime :(

Any ideas on how I can get this working both ways?

Renato
  • 12,940
  • 3
  • 54
  • 85
  • 1
    `YYYY` is probably a better choice than `Y`. – Joe C Mar 17 '18 at 20:37
  • @JoeC just to clarify, this is a Java question, not a Groovy question... I used Groovy to write the example as it's much easier to test the Java API using the Groovy console in IntelliJ :) But my code is Java and Groovy is only used to consume the Java API in this case. – Renato Mar 17 '18 at 20:39
  • "when trying to parse this text back" - How, exactly? – Abhijit Sarkar Mar 17 '18 at 20:53
  • 1
    Read the code above. 3rd last line. – Renato Mar 17 '18 at 20:54
  • The 3rd last line is "and it does parse successfully!! But then, the return type is TemporalAccessor and I do really need" – Abhijit Sarkar Mar 17 '18 at 20:57
  • @AbhijitSarkar I mean third last line of the code snippet! I edited the post to make that clearer. – Renato Mar 17 '18 at 20:58
  • @sotirios-delimanolis please unmark this as a duplicate! That answer is completely unrelated to this, and does not fix the problem in any way. – Renato Mar 17 '18 at 21:04
  • [Works for me.](https://ideone.com/xAnYSk) Please explain what the problem is after you change the pattern character intended to be the year. – Sotirios Delimanolis Mar 17 '18 at 21:06
  • @SotiriosDelimanolis Ah, sorry. I forgot to turn back to the old code after I made other changes. Thanks. – Renato Mar 17 '18 at 21:07

0 Answers0