fiddle
fiddle

Reputation: 1164

Java - Unparseable date exception

I have a date object which has date in the format: 2015-09-21 10:42:48:000 I want it to be displayed on the UI in this format.21-Sep-2015 10:42:48

The code I am using is not working and throws this:

Unparseable date exception: Unparseable date: "2015-09-21 10:42:48"

Here is the actual code:

 String createdOn=f.getCreatedOn().toString();//f.getCreatedOn() returns a date object
 SimpleDateFormat format=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
 Date date=format.parse(createdOn.substring(0,createdOn.length()-3));
 log.debug(">>>>>>date now is: "+date);
 model.addAttribute("date", date);
 model.addAttribute("info", messages);
 SimpleDateFormat format1=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
 format1.format(date);
 log.debug(">>>>>>date now is again: "+date);

Upvotes: 0

Views: 525

Answers (3)

SatyaTNV
SatyaTNV

Reputation: 4135

Unparseable date exception: Unparseable date: "2015-09-21 10:42:48"

Since your input date format is yyyy-MM-dd HH:mm:ss. But you are trying parsing with dd-MMM-yyyy HH:mm:ss format.

SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//change input date format here
Date date=format.parse("2015-09-21 10:42:48:000");
//Date date=format.parse(createdOn);//Here no need of subtracting 000 from your date
SimpleDateFormat format1=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
System.out.println(format1.format(date));

SimpleDateFormat doc

Upvotes: 2

Saj
Saj

Reputation: 18712

You are using wrong format to display and parse.

// We will use this for parsing a string that represents a date with the format declared below. If you try to parse a date string with a different format, you will get an exception like you did   
SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// This is for the way we want it to be displayed
SimpleDateFormat displayFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");

// Parse the date string
Date date = parseFormat.parse("2015-09-21 10:42:48:000");

// Format the date with the display format
String displayDate = displayFormat.format(date);

System.out.println(">>>>>>date now is: " + displayDate);

Upvotes: 0

vijay
vijay

Reputation: 494

Your input date format is different.

String createdOn="2015-09-21 10:42:48:000";
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=format.parse(createdOn.substring(0,createdOn.length()-4));
        System.out.println(">>>>>>date now is: "+date);

        SimpleDateFormat format1=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
        format1.format(date);
        System.out.println(">>>>>>date now is again: "+date);

Upvotes: 0

Related Questions