Parsing RFC 2822 date in JAVA

Chris Dutrow picture Chris Dutrow · Mar 16, 2010 · Viewed 14.9k times · Source

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!

Answer

Buhake Sindi picture Buhake Sindi · Mar 16, 2010

This is quick code that does what you ask (using SimpleDateFormat)

String rfcDate = "Sat, 13 Mar 2010 11:29:05 -0800";
String pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date javaDate = format.parse(rfcDate);

//Done.

PS. I've not dealt with exceptions and concurrency here (as SimpleDateFormat is not synchronized when parsing date).