简体   繁体   中英

How to convert the date and time in any timezone in the Gmail to the UTC format using java

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.

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, eg, using SimpleDateFormat .

Obsolete format

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.

java.time

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM