How do I parse a date string using DateFormat?

11,217

Solution 1

The issue was that I was trying to parse an English date while in the French locale.

This was resolved by using this instead:

SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.CANADA);

Solution 2

Are you sure that date string is really being assigned the value Thu Oct 20 14:39:19 PST 2011? If that's not the problem, you could try using this code which works for me:

import java.text.SimpleDateFormat;
import java.util.Date;
public class Test{


  public static void main(String args[]){

    String toParse = "Thu Oct 20 14:39:19 PST 2011";

    String format = "EEE MMM dd HH:mm:ss z yyyy";
    SimpleDateFormat formater = new SimpleDateFormat(format);
    try{
      Date parsed = formater.parse(toParse);
    } catch(Exception e){
      System.out.println(e.getMessage());
    }

  }
}
Share:
11,217
howettl
Author by

howettl

I am a professional mobile software developer living in Vancouver BC. I graduated from the University of Victoria with a B Sc in Computer Science.

Updated on June 04, 2022

Comments

  • howettl
    howettl almost 2 years

    I have a date string in the following format:

    Thu Oct 20 14:39:19 PST 2011

    I would like to parse it using DateFormat to get a Date object. I'm trying it like this:

    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
    Date date = df.parse(dateString);
    

    This gives a ParseException ("unparseable date").

    I've also tried this:

    SimpleDateFormat df = new SimpleDateFormat("EEE-MMM-dd HH:mm:ss z yyyy");
    

    with the same results.

    Is that the right SimpleDateFormat string? Is there a better way to parse this date?