Pit Digger
Pit Digger

Reputation: 9800

SimpleDateFormat String

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());

Upvotes: 16

Views: 61343

Answers (3)

Kal
Kal

Reputation: 24910

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);

Upvotes: 30

Marcelo
Marcelo

Reputation: 11308

If you need to read a Date with one String format and output it to another String format, you need 2 formatters, for example:

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat outputFormat = new SimpleDateFormat("MMMMM dd, yyyy");
String output = outputFormat.format(inputFormat.parse(input));

Upvotes: 4

Bozho
Bozho

Reputation: 597106

There are two applications of SimpleDateFormat:

  • parse a string - when you have a date represented as string, and you want to get the corresponding Date object. Then use dateFormat.parse(string)

  • format a date - when you have a Date object and you want to format it in a specific way (usually in order to show it to a user). In that case use dateFormat.format(date)

The two methods are reciprocal - one takes a date and returns a string, and the other takes a string and returns a date.

For your particular case, perhaps you need .parse(..). But note that every 'self-respecting' database driver should have an option to return a Date rather than some string representation. If you happen to be storing dates as string in the DB - don't do that. Use the native date type.

Upvotes: 6

Related Questions