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());
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.
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).
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With