[英]SimpleDateFormat parsing date string incorrectly
我正在尝试将字符串解析为日期,然后将该日期格式化为其他字符串格式以进行输出。
我的日期格式代码如下:
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")
的结果是sysObj.getString("document_date")
1/31/2013 12:00:01 AM
。 当我检查formattedDocumentDate
的值时,得到01/07/2015
。
任何帮助深表感谢。
您将第31
天解析为月份。 SimpleDateFormat
尝试为您提供有效日期。 因此,它增加了1/0/2013 31个月 。 这是2年7个月。 这样您就可以得到结果01/01/2015 。 因此, SimpleDateFormat
可以正常工作。
一种解决方案是将日期格式更改为M/d/yyyy h:m:sa
或输入数据。
为避免这些尝试,您必须关闭SimpleDateFormat
宽松模式。 如果格式不合适,您将获得一个例外。
看来您的输入格式实际上是先几个月,然后是几天。 因此应为“ 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")));
这样的另一个例子
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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.