views:

540

answers:

4

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

A: 

Extract the data from the header using some sort of substring or regular expression. Parse the date with a SimpleDateFormatter to create a Date object.

Joshua
Thanks jhawk28. However I can get the Date using the MailDateFormat class. That class also parses the timezone, but there seems to be no easy way to find that TimeZone, except for copying code from MailDateParser.
mmartijn
+1  A: 

ref: http://jimyjoshi.com/blog/2007/08/rfc822dateparsinginjava.html for parsing dates.

Times must always be stored in UTC (GMT) - i.e. after parsing convert from the timezone to GMT and remove daylight savings offset.

You can stored the date with the timezone.

If you remove or don't handle the timezone it can cause problems when dealing with data that has come from a different timezone.

Richard Harrison
A: 

The timezone in the email will not show in which timezone it was send. Some programs use ever UTC or GMT. Of course the time zone is part of the date time value and must also be parse.

Why do you want know it. - Do you want normalize the timestamp? Then use a DateFormat for parsing it. - Do you want detect the timezome of the user that send the email? This will not correctly work.

Horcrux7
I want to detect the timezone of the user that sent the email. Why wouldn't this work?
mmartijn
Because some programs send ever UTC or GMT time independent of the timezone of the user. It is the timezone of the formated Date String and not of the user computer.
Horcrux7
A: 

It looks like you already mentioned this in one of your comments, but I think it's your best answer. The JavaMail library contains RFC822 Date header parsing code in javax.mail.internet.MailDateFormat. Unfortunately it doesn't expose the TimeZone parsing directly, so you will need to copy the necessary code directly from javax.mail.internet.MailDateParser, but it's worth taking advantage of the careful work already done.

As for storing it, the parser will give you the date as an offset, so you should be able to store it just fine as an int (letting Hibernate translate that to your database for you).

Dave L.