8

This is the date format that I need to deal with

Wed Aug 21 2013 00:00:00 GMT-0700 (PDT)

But I don't get what the last two parts are. Is the GMT-0700 fixed? Should it be something like this?

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT-0700' (z)");
Cacheing
  • 3,431
  • 20
  • 46
  • 65

2 Answers2

15

No, it is not fixed. It is a TimeZone. You can match it with Z in the date format.

To be more precise, in SimpleDateFormat formats :

  • Z matches the -0700 part.
  • GMT is fixed. Escape it with some quotes.
  • z matches the PDT part. (PDT = Pacific Daylight Time).
  • The parenthesis around PDT are fixed. Escape them with parenthesis.

You can parse your date with the following format :

EEE MMM dd yyyy HH:mm:ss 'GMT'Z '('z')'

Another remark : Wed Aug contains the day and month in English so you must use an english locale with your SimpleDateFormat or the translation will fail.

new SimpleDateFormat("*format*", Locale.ENGLISH);
Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
  • wait, i don't get it. According to the document: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html, `z` matches `GMT` part, and `Z` matches the `-0700` part. – Cacheing Aug 28 '13 at 17:13
  • According to this doc, `z` can match `GMT-08:00`, not `GMT-0800`. That's why you must isolate the `GMT` part manually. `z` can also catch `GMT` alone but it would be considered as `GMT+00:00`. Hence, it would not make sense to have another `Z` (`GMT+00:00 -0700` => 2 Timezones). – Arnaud Denoyelle Aug 28 '13 at 17:35
  • Sorry, it is a typo. I mean `z` matches `PDT`, and `Z` matches `-0700`. I think you should switch `z` and `Z` here, is it right? – Cacheing Aug 28 '13 at 17:49
  • True! (I edited) Actually, that code worked by chance and I found why : `z` is the `General time zone` but the javadoc tells that for parsing, simple timezones are accepted and conversely. – Arnaud Denoyelle Aug 28 '13 at 17:57
4

Here is the Javadoc:

http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

For this example: Wed Aug 21 2013 00:00:00 GMT-0700 (PDT), you'd want this format:

import java.text.SimpleDateFormat;
import java.util.Date;

public class JavaDate {

  public static void main (String[] args) throws Exception {

    String s= "Wed Aug 21 2013 00:00:00 GMT-0700 (PDT)";
    SimpleDateFormat sdf = 
      new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'z '('Z')'");
    Date d = sdf.parse (s);
    System.out.println ("Date=" + d + "...");
  }
}

EXAMPLE OUTPUT: Date=Tue Aug 20 23:00:00 PDT 2013...

Thanx to Arnaud Denoyelle above for his edits!

paulsm4
  • 114,292
  • 17
  • 138
  • 190