SimpleDateFormat String

Pit Digger picture Pit Digger · Aug 22, 2011 · Viewed 49.1k times · Source

I have this code block where argument to dateFormat.format will always be a string thats why I did .toString() here. I am getting error "Cannot format given Object as a Date".

Is there any way to do this ? Note that string is coming from database I used new Date() as a sample here.

SimpleDateFormat dateFormat = new SimpleDateFormat("MMMMM dd, yyyy");
String sCertDate = dateFormat.format(new Date().toString());

Answer

Kal picture Kal · Aug 22, 2011

DateFormat#format accepts a Date, not a string.

Use

String sCertDate = dateFormat.format(new Date());

If you have a string coming from the database that is a specific format and you want to convert into a date, you should use the parse method.

@Sonesh - Let us assume you have a string in the database that happens to represent a Date ( might be better to store the object in the database as dates? ) , then you would first parse it to the format you wanted and then format it to the string format you wanted.

// Assumes your date is stored in db with format 08/01/2011
SimpleDateFormat dateFormatOfStringInDB = new SimpleDateFormat("MM/dd/yyyy");
Date d1 = dateFormatOfStringInDB.parse(yourDBString);
SimpleDateFormat dateFormatYouWant = new SimpleDateFormat("MMMMM dd, yyyy");
String sCertDate = dateFormatYouWant.format(d1);