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?