我试图将String解析为Date,然后将该Date格式化为不同的String格式以便输出。
我的日期格式代码如下:
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat dateParser = new SimpleDateFormat("d/M/yyyy h:m:s a");
String formattedDocumentDate = dateFormatter.format(dateParser.parse(sysObj.getString("document_date")));
sysObj.getString("document_date")
的结果是1/31/2013 12:00:01 AM
。当我检查formattedDocumentDate
的值时,我会01/07/2015
。
非常感谢任何帮助。
答案 0 :(得分:3)
您要将天数31
解析为几个月。 SimpleDateFormat
试图给你一个有效的约会。因此,它增加到1/0/2013 31个月。这是2年零7个月。因此,您获得的结果 01/07/2015 。所以SimpleDateFormat
工作正确。
一种解决方案是将日期模式更改为M/d/yyyy h:m:s a
或输入数据。
要避免这些尝试,您必须关闭SimpleDateFormat
宽松模式。如果格式不合适,您将获得异常。
答案 1 :(得分:2)
看起来您的输入格式实际上是几个月,然后是几天。所以应该是“MM / dd / yyyy”。 所以:
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/M/yyyy");
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
String formattedDocumentDate = dateFormatter.format(dateParser.parse(sysObj.getString("document_date")));
答案 2 :(得分:0)
另一个类似的例子
SimpleDateFormat sdfInput = new SimpleDateFormat("yyyyMMdd");
System.out.println("date is:"+new java.sql.Date( sdfInput.parse("20164129").getTime() ));
输出为:2019-05-29
我希望引发解析异常,但不是(41)不是有效的月份值。
另一方面,如果我给了20170229
,系统可以识别出2017年2月没有圈速,并返回2017-03-01
有趣。