SimpleDateFormat 中的两位数年份
Two-digit year in SimpleDateFormat
也许这个问题很傻,但我没有找到令我满意的答案。
我有一个像这样的 SimpleDataFormat:
sdf = new SimpleDateFormat("dd/MM/yyyy");
如果我尝试解析这样的日期:10/10/15
那么日期结果是 15 年,而不是 2015 年。
为什么 parse
在这种情况下有效?我期待 ParseException
如何强制用户以 4 位格式输入年份? (没有String.length()
请)
我正在使用 setLenient(false)
这是因为当您说 dd/MM/yyyy
时,java 希望您提供 'full year',但不一定必须是 4 位数年份。它类似于 MMMMM
- 这并不意味着您只需要月份的 5 个字符,这意味着您需要完整的月份名称。我相信您将不得不使用 String.length(),或者您可以解析它并检查日期范围。
您的日期按字面解释。每 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."
这也是您没有得到预期异常的原因。
也许这个问题很傻,但我没有找到令我满意的答案。
我有一个像这样的 SimpleDataFormat:
sdf = new SimpleDateFormat("dd/MM/yyyy");
如果我尝试解析这样的日期:10/10/15
那么日期结果是 15 年,而不是 2015 年。
为什么 parse
在这种情况下有效?我期待 ParseException
如何强制用户以 4 位格式输入年份? (没有String.length()
请)
我正在使用 setLenient(false)
这是因为当您说 dd/MM/yyyy
时,java 希望您提供 'full year',但不一定必须是 4 位数年份。它类似于 MMMMM
- 这并不意味着您只需要月份的 5 个字符,这意味着您需要完整的月份名称。我相信您将不得不使用 String.length(),或者您可以解析它并检查日期范围。
您的日期按字面解释。每 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."
这也是您没有得到预期异常的原因。