简体   繁体   English

SimpleDateFormat解析日期字符串不正确

[英]SimpleDateFormat parsing date string incorrectly

I'm trying to parse a String into a Date and then format that Date into a different String format for outputting. 我正在尝试将字符串解析为日期,然后将该日期格式化为其他字符串格式以进行输出。

My date formatting code is as follows: 我的日期格式代码如下:

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")));

The result of sysObj.getString("document_date") is 1/31/2013 12:00:01 AM . sysObj.getString("document_date")的结果是sysObj.getString("document_date") 1/31/2013 12:00:01 AM And when I check the value of formattedDocumentDate I get 01/07/2015 . 当我检查formattedDocumentDate的值时,得到01/07/2015

Any help is much appreciated. 任何帮助深表感谢。

You are parsing days 31 as months. 您将第31天解析为月份。 SimpleDateFormat tries to give you a valid date. SimpleDateFormat尝试为您提供有效日期。 Therefore It adds to 1/0/2013 31 months . 因此,它增加了1/0/2013 31个月 This is 2 years and 7 month. 这是2年7个月。 So you get your result 01/07/2015 . 这样您就可以得到结果01/01/2015 So SimpleDateFormat works correct. 因此, SimpleDateFormat可以正常工作。

One solution for you is to change your date pattern to M/d/yyyy h:m:sa or your input data. 一种解决方案是将日期格式更改为M/d/yyyy h:m:sa或输入数据。

To avoid these tries you have to switch off SimpleDateFormat lenient mode. 为避免这些尝试,您必须关闭SimpleDateFormat宽松模式。 Then you will get an exception if the format does not fit. 如果格式不合适,您将获得一个例外。

It looks like your input format is actually months first, then days. 看来您的输入格式实际上是先几个月,然后是几天。 So should be "MM/dd/yyyy". 因此应为“ MM / dd / yyyy”。 So: 所以:

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")));

Another example like this 这样的另一个例子

SimpleDateFormat sdfInput = new SimpleDateFormat("yyyyMMdd");
System.out.println("date is:"+new java.sql.Date( sdfInput.parse("20164129").getTime() ));

Output is: 2019-05-29 输出是: 2019-05-29

I expect to throw parse exception but not (41)is not a valid month value. 我希望引发解析异常,但(41)不是有效的月份值。 on the other hand if I gave 20170229 , system can recognize the February of 2017 doesn't have a lap year and return 2017-03-01 interesting. 另一方面,如果我给出了20170229 ,系统可以识别出2017年2月没有圈数,并返回有趣的2017-03-01

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM