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)?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With