Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a date string using DateFormat?

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?

like image 397
howettl Avatar asked Dec 21 '22 07:12

howettl


1 Answers

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());
    }

  }
}
like image 159
Kurtis Nusbaum Avatar answered Dec 28 '22 11:12

Kurtis Nusbaum