tags:

views:

4112

answers:

3

i am trying to parse this date with SimpleDateFormat and it doesnt work :

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

/**
 *
 * @author fennec
 */
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.

+3  A: 

The problem is that you have a date formatted like this:

Thu Jun 18 20:56:02 EDT 2009

but are using a SimpleDateFormat that is

yyyy-MM-dd

The two formats don't agree. You need to construct a SimpleDateFormat that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat like this:

EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009

Check the JavaDoc page I linked to and see how the characters are used.

Eddie
+14  A: 

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 parserSDF=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");

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

larson4
This is the precise answer, IMHO.
Nordin
+1  A: 

How about getSelectedDate? Anyway, specifically on your code question, the problem is with this line:

new SimpleDateFormat("yyyy-MM-dd");

The string that goes in the constructor has to match the format of the date. The documentation for how to do that is here. Looks like you need something close to "EEE MMM d HH:mm:ss zzz yyyy"

Yishai