Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 726
mmartijn Avatar asked Sep 20 '08 13:09

mmartijn


People also ask

How to get TimeZone from DateTime in Java?

The getTimeZone() method in DateFormat class is used to return the current time-zone of the calendar of this DateFormat. Parameters: The method does not take any parameters. Return Value: The method returns timezone associated with the calendar of DateFormat.

How to convert TimeZone Date into Date format in Java?

This code does what I want for the CURRENT TIME: Calendar calendar = new GregorianCalendar(TimeZone. getTimeZone("GMT")); DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z"); formatter. setTimeZone(TimeZone.

Does Java Date contain TimeZone?

The java. util. Date has no concept of time zone, and only represents the number of seconds passed since the Unix epoch time – 1970-01-01T00:00:00Z. But, if you print the Date object directly, the Date object will be always printed with the default system time zone.

How do you find the time zone with date and time?

To get the current browser's time zone, you can use the getTimezoneOffset() method from the JavaScript Date object. The getTimezoneOffset() returns the time difference, in minutes, between UTC time and local time.


1 Answers

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.

like image 113
Adam Gent Avatar answered Sep 29 '22 00:09

Adam Gent