I need to parse an RFC 2822 string representation of a date in Java. An example string is here:
Sat, 13 Mar 2010 11:29:05 -0800
It looks pretty nasty so I wanted to make sure I was doing everything right and would run into weird problems later with the date being interpreted wrong either through AM-PM/Military time problems, UTC time problems, problems I don't anticipate, etc...
Thanks!
Since Java 8 new datetime classes were implemented:
java.time.ZonedDateTime
andjava.time.LocalDateTime
.ZonedDateTime
supports the parsing of RFC strings nearly out of the box:If your application is using another language than English, you may want to force the locale for the date parsing/formatting by using an alternate SimpleDateFormat constructor:
This is quick code that does what you ask (using SimpleDateFormat)
PS. I've not dealt with exceptions and concurrency here (as SimpleDateFormat is not synchronized when parsing date).
Please keep in mind that the [day-of-week ","] is optional in RFC-2822, hence the suggested examples are not covering all RFC-2822 date formats. Additional, the RFC-822 date type allowed many different time zone notations(obs-zone), which are not covered by the "Z" format specifier.
I guess there is no easy way out, other than looking for "," and "-|+" to determine which pattern to use.