Priyank Thakkar
Priyank Thakkar

Reputation: 4852

Java SimpleDateFormat: Unparseable Date exception

The code is as mentioned below:

public static void main(String[] args){
    Date date = new Date();
    DateFormat dateFormat= new SimpleDateFormat("dd-MMM-yyy");

    try{
        Date formattedDate = dateFormat.parse(date.toString());
        System.out.println(formattedDate.toString());
    }catch(ParseException parseEx){
        parseEx.printStackTrace();
    }
}

In code above, dateFormat.parse(date.toString()) is throwing unparseable date exception: Unparseable date: "Mon Jan 28 18:53:24 IST 2013

I am not able to figure out the reason for it.

Upvotes: 0

Views: 42024

Answers (3)

PermGenError
PermGenError

Reputation: 46428

Format the java.util.Date instance into String using SimpleDateFormat.format(java.util.Date)

Date date = new Date();
DateFormat dateFormat= new SimpleDateFormat("dd-MMM-yyy");

try {
    Date formattedDate = dateFormat.parse(dateFormat.format(date));
    System.out.println(formattedDate.toString());

} catch (ParseException parseEx) {
   parseEx.printStackTrace();
}

Upvotes: 5

Achintya Jha
Achintya Jha

Reputation: 12843

public static void main(String[] args) throws ParseException {

    Date date = new Date();
    DateFormat dateFormat = new SimpleDateFormat(
            "EEE MMM d HH:mm:ss Z yyyy");

    Date formattedDate = dateFormat.parse(date.toString());
    System.out.println(formattedDate);

}

This is what you exactly want to do ...yes?

Upvotes: 2

Kurt Du Bois
Kurt Du Bois

Reputation: 7665

Why would you want to convert a date to a string and parse it back to a date?

The reason your code fails is because you are trying to convert a full date with a formatter which only accepts dates in the dd-MMM-yyy-format.

Upvotes: 4

Related Questions