javadatetimedatetime-formatsimpledateformatdatetime-parsing

SimpleDateFormat doesn't maintain timezone


i have a date object in the following format:

Sun Jan 20 10:12:27 GMT+02:00 2013

the above time appears in microsoft outlook correctly:

Sun 1/20/2013 12:12 PM (this is the time in GMT+2 >> client timezone)

when trying to format the date object with SimpleDateFormat to appear as in the outlook, using the following code:

SimpleDateFormat sdf=new SimpleDateFormat(
    "EEE M/d/yyyy hh:mm a");
    String receivedDate = sdf.format(email.getDateTimeReceived());

the result of formatting is:

Sun 1/20/2013 10:12 AM

so the two hours of the timezone difference are missing.

please advise how to fix that, thanks.


Solution

  • If I understand correctly, you want to format the date using the GMT time zone.

    DateFormat dateFormat = new SimpleDateFormat("EEE M/d/yyyy hh:mm a");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String formattedDate = dateFormat.format(date);