SimpleDateFormat字符串 [英] SimpleDateFormat String
问题描述
我有这个代码块,其中 dateFormat.format
的参数将始终是字符串
这就是为什么我 .toString()
这里。我收到错误无法将给定对象格式化为日期。
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".
有没有办法做到这一点?请注意,字符串来自数据库我在这里使用了新的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());
推荐答案
DateFormat#format 接受日期,而不是字符串。
DateFormat#format accepts a Date, not a string.
使用
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 - 假设您在数据库中有一个恰好代表日期的字符串(可能更适合存储数据库中的对象作为日期?),然后你首先解析
它到你想要的格式然后格式
它是您想要的字符串格式。
@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);
这篇关于SimpleDateFormat字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!