What is the Date Format for "Fri Jun 05 00:00:00 PDT 2015"

1.2k views Asked by At

I am trying to determine what java date format string to use for

"Fri Jun 05 00:00:00 PDT 2015"

Right now I am using

SimpleDateFormat format = new SimpleDateFormat("EEE MM dd HH:mm:ss zzzz yyyy");

But this yields

  com.fasterxml.jackson.databind.JsonMappingException: 
  java.text.ParseException: Unparseable date: "Fri Jun 05 00:00:00 PDT 2015" 
  (through reference chain:....
2

There are 2 answers

2
M A On BEST ANSWER

You need one additional M for the month:

EEE MMM dd HH:mm:ss zzzz yyyy

This is mentioned in the Javadocs of SimpleDateFormat:

Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.

0
Arvind Kumar Avinash On

Locale is as important as the pattern

Irrespective of the applicable pattern, it's important to use Locale as a date-time parsing/formatting type (e.g. the smart and vivid DateTimeFormatter of the modern API, or the notorious and error-prone SimpleDateFormat of the legacy API) is Locale-sensitive. Since your date-time string is in English, you should use Locale.ENGLISH.

Note that the legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.

Demo using modern date-time API:

For the abbreviated month name, you need to use MMM instead of MM.

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String args[]) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM d H:m:s zzz u", Locale.ENGLISH);
        ZonedDateTime zdt = ZonedDateTime.parse("Fri Jun 05 00:00:00 PDT 2015", dtf);
        System.out.println(zdt);
    }
}

Output:

2015-06-05T00:00-07:00[America/Los_Angeles]

For whatsoever reason, if you need an instance of java.util.Date from this object of ZonedDateTime, you can do so as follows:

Date date = Date.from(zdt.toInstant());

Learn more about the the modern date-time API* from Trail: Date Time.

Note: Ask your publisher to send the timezone name in the format, Region/City as shown in the above output. The three-letter timezone name (e.g. PDT) is ambiguous and hence, error-prone.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.