我有这个代码块,这里的参数dateFormat.format
始终是string
多数民众赞成在我.toString()
这里做的原因。我收到错误消息“无法将给定对象格式化为日期”。
有什么办法吗?请注意,字符串来自数据库,我在这里使用new Date()作为示例。
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMMM dd, yyyy");
String sCertDate = dateFormat.format(new Date().toString());
DateFormat#format接受日期,而不是字符串。
用
String sCertDate = dateFormat.format(new Date());
如果您有来自数据库的特定格式的字符串,并且想要转换为日期,则应使用parse方法。
@Sonesh-让我们假设您在数据库中有一个字符串,恰好代表一个Date(将对象存储在数据库中作为日期会更好吗?),然后将其首先设置parse
为所需的格式,然后将format
其设置为您想要的字符串格式。
// 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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句