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