java – SimpleDateFormat String

I have this code block, where dateformat The format parameter will always be a string, which is why I do this ToString () is here I received the error "unable to format the given object as a date"

Is there any way to do this? Note that the string comes from the database, and I use the new date () as an example

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

Solution

Dateformat #format accepts dates, not strings

use

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

If you have a string from the database in a specific format and want to convert it to a date, you should use the parse method

@Sonesh – let's assume that you have a string in the database that exactly represents a date (it may be best to store the object in the database as a date), then you first parse it into the format you want, and then format it into the string format you want

// 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);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>