Two-digit year in SimpleDateFormat

▼魔方 西西 提交于 2020-06-28 02:53:23

问题


Maybe this question is fool, but I didn't have found any answer that has satisfied me.

I have a SimpleDataFormat like:

sdf = new SimpleDateFormat("dd/MM/yyyy");

And if I try to parse a date like: 10/10/15

Then the Date result is for year 15, and not 2015.

Why the parse works in this case? I was expecting a ParseException

How I force the user to put year in 4 digit format? (Without String.length() please)

I'm using setLenient(false)


回答1:


Your date is interpreted literally. Per http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

"For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D."

This is also why you didn't get the exception that you expected.




回答2:


This is because when you say dd/MM/yyyy, java expects you to provide the 'full year', but its not necessary that it has to be 4-digit years. Its similar to MMMMM - this doesn't mean you want only 5 characters of the month, it means you want the full month name. I believe you will have to use String.length(), or you may parse it and check for date range.



来源:https://stackoverflow.com/questions/30398112/two-digit-year-in-simpledateformat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!