Reputation: 11
I want to convert the dates which are available in the mail headers in timezones like PST or PDT to the UTC format using java.
For example:
Tue, 21 Apr 2015 07:12:18 -0700 (PDT). This is the date which will be in the string variable. I want to convert this date into the UTC format.This date is not the current system date. Please suggest me the solution of the problem in java.
Upvotes: 1
Views: 537
Reputation: 339917
Your example data is odd. As I recall the old email standards use RFC 1123 or RFC 822. Your format is similar, but missing the colon between hour and minute of the offset, and has extraneous parens around the pseudo-zone.
Be aware that such formats are obsolete. They are difficult to parse by machine. And they assume English language and particular cultural norms. Modern protocols adopted ISO 8601 formats instead. The ISO 8601 formats are used by default in the java.time classes.
If you really must parse text in that specific format, define a DateTimeFormatter
to match its formatting pattern.
String input = "Tue, 21 Apr 2015 07:12:18 -0700 (PDT)";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE, dd MMM uuuu HH:mm:ss XXXX '('z')'" ).withLocale( Locale.US );
Parse as a ZonedDateTime
.
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
zdt.toString(): 2015-04-21T07:12:18-07:00[America/Los_Angeles]
Note that PDT
is not a real time zone names. Never use these 2-4 letter pseudo-zones. Real time zones have a name in Continent/Region
format such as America/Los_Angeles
.
Upvotes: 1
Reputation: 29971
Assuming you're using the MimeMessage getSentDate or getReceivedDate methods, you'll get a Date object that's already properly converted. You just need to format and display the date however you want, e.g., using SimpleDateFormat.
Upvotes: 1
Reputation: 5999
For that conversion, you will need a good time library that takes into consideration daylight saving time, etc. A great one for java is Joda. The library permits a variety of formatting options, for both inputs and outputs, to solve your problem. Look at the documentation for samples.
Upvotes: 0