Java – Best way to extract a timezone from a mail Date header in Java

jakarta-mailjavatimezone

I need to store the timezone an email was sent from. Which is the best way to extract it from the email's 'Date:' header (an RFC822 date)? And what is the recommended format to store it in the database (I'm using hibernate)?

Best Solution

I recommend you use Mime4J.

The library is designed for parsing all kinds of email crap. For parsing dates you would use its DateTimeParser.

int zone = new DateTimeParser(new StringReader("Fri, 27 Jul 2012 09:13:15 -0400")).zone();

After that I usually convert the datetimes to Joda's DateTime. Don't use SimpleDateFormatter as will not cover all the cases for RFC822.

Below will get you the Joda TimeZone (from the int zone above) which is superior to Java's TZ.

// Stupid hack in case the zone is not in [-+]zzzz format
final int hours;
final int minutes;
if (zone > 24 || zone < -24 ) {
    hours = zone / 100;
    minutes = minutes = Math.abs(zone % 100);
}
else {
    hours = zone;
    minutes = 0;
}
DateTimeZone.forOffsetHoursMinutes(hours, minutes);

Now the only issue is that the Time Zone you will get always be a numeric time zone which may still not be the correct time zone of the user sending the email (assuming the mail app sent the users TZ and not just UTC).

For example -0400 is not EDT (ie America/New_York) because it does not take Daylight savings into account.