How to parse a date?

fenec picture fenec · Jun 16, 2009 · Viewed 406.6k times · Source

I am trying to parse this date with SimpleDateFormat and it is not working:

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

public class Formaterclass {
    public static void main(String[] args) throws ParseException{
        String strDate = "Thu Jun 18 20:56:02 EDT 2009";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date dateStr = formatter.parse(strDate);
        String formattedDate = formatter.format(dateStr);
        System.out.println("yyyy-MM-dd date is ==>"+formattedDate);
        Date date1 = formatter.parse(formattedDate);

        formatter = new SimpleDateFormat("dd-MMM-yyyy");
        formattedDate = formatter.format(date1);
        System.out.println("dd-MMM-yyyy date is ==>"+formattedDate);
    }
}

If I try this code with strDate="2008-10-14", I have a positive answer. What's the problem? How can I parse this format?

PS. I got this date from a jDatePicker and there is no instruction on how modify the date format I get when the user chooses a date.

Answer

jwl picture jwl · Jun 16, 2009

You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.

To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):

SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");

Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.

        String input = "Thu Jun 18 20:56:02 EDT 2009";
        SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
        Date date = parser.parse(input);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = formatter.format(date);

        ...

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