SimpleDateFormat中的两位数年份 [英] Two-digit year in SimpleDateFormat
问题描述
也许这个问题很愚蠢,但是我没有找到任何令我满意的答案。
Maybe this question is fool, but I didn't have found any answer that has satisfied me.
我有一个SimpleDataFormat,如:
I have a SimpleDataFormat like:
sdf = new SimpleDateFormat("dd/MM/yyyy");
如果我尝试解析日期,例如: 10/10/15
And if I try to parse a date like: 10/10/15
然后,日期结果是第15年,而不是2015年。
Then the Date result is for year 15, and not 2015.
为什么 parse
在这种情况下有效?我期待一个 ParseException
Why the parse
works in this case? I was expecting a ParseException
我如何强制用户将年份以4位数格式输入? (请不要使用 String.length()
)
How I force the user to put year in 4 digit format? (Without String.length()
please)
我正在使用 setLenient(false )
推荐答案
您的日期按字面意义进行解释。每个 http://docs.oracle.com/javase /6/docs/api/java/text/SimpleDateFormat.html
Your date is interpreted literally. Per http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
对于解析,如果模式字母的数量大于在图2中,
年将按字面意义进行解释,而不考虑位数。因此,
使用模式 MM / dd / yyyy, 01/11/12解析为公元12年1月11日。
"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.
这篇关于SimpleDateFormat中的两位数年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!