Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
like image 723
Pit Digger Avatar asked Aug 22 '11 16:08

Pit Digger


People also ask

What is SimpleDateFormat text?

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.

Is SimpleDateFormat thread-safe?

SimpleDateFormat is not thread-safe in any JDK version, nor will it be as Sun have closed the bug/RFE. Only formatting is supported, but all patterns are compatible with SimpleDateFormat (except time zones - see below).

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

Is SimpleDateFormat deprecated?

Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.


1 Answers

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);
like image 197
Kal Avatar answered Sep 30 '22 18:09

Kal