SimpleDateFormat字符串

挖坑机

我有这个代码块,这里的参数dateFormat.format始终是string多数民众赞成在我.toString()这里做的原因我收到错误消息“无法将给定对象格式化为日期”。

有什么办法吗?请注意,字符串来自数据库,我在这里使用new Date()作为示例。

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

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

SimpleDateFormat的解析字符串的日期是错误

SimpleDateFormat解析非日期字符串

在SimpleDateFormat模式字符串中使用字母字符

当字符串中也存在时,SimpleDateFormat忽略TimeZone

用字符串格式化 SimpleDateFormat

无法使用 SimpleDateFormat 解析字符串日期

日期字符串在SimpleDateFormat中的解析不正确

SimpleDateFormat和基于语言环境的格式字符串

如何使用SimpleDateFormat将字符串转换为日期?

DateTimeFormatter无法解析日期字符串,但SimpleDateFormat能够

使用SimpleDateFormat将字符串转换为日期

如何使用simpledateformat将字符串转换为日期

DateTimeFormatter 和 SimpleDateFormat 使用相同的输入字符串产生不同的结果

使用SimpleDateFormat将字符串解析为日期,毫秒数变化

为什么SimpleDateFormat.parse接受无效的日期字符串?

Java SimpleDateFormat将解析字符串解释为UTC

如何减去一个SimpleDateFormat和一个字符串

如何从当前Locale获取日期时间格式字符串,为SimpleDateFormat的参数

使用simpleDateFormat将字符串转换为Util日期不起作用

为什么SimpleDateFormat无法在日期字符串中解析工作日?

为什么使用SimpleDateFormat从字符串中解析日期时得到错误的结果?(Java)

SimpleDateFormat在格式化为字符串时会添加随机毫秒

当将无效字符串传递给JAVA中的SimpleDateFormat时引发异常

为什么此SimpleDateFormat无法解析此日期字符串?

Java-SimpleDateFormat字符串将Date转换为Mills

使用simpledateformat解析字符串日期为6毫秒的日期

SimpleDateFormat.format() 没有返回正确格式的日期字符串

如何正确格式化DateTimePicker中的日期字符串以通过SimpleDateFormat进行解析?

SimpleDateFormat:ParseException,但是字符串日期看起来还可以