为什么SimpleDateFormat(“MM / dd / yyyy”)将日期解析为10/20/20128? [英] Why SimpleDateFormat("MM/dd/yyyy") parses date to 10/20/20128?

查看:148
本文介绍了为什么SimpleDateFormat(“MM / dd / yyyy”)将日期解析为10/20/20128?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

  DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
  dateFormat.setLenient(false);
  Date date = dateFormat.parse("10/20/20128");

我希望dateFormat.parse调用抛出ParseException,因为我提供的年份是5字符长而不是4,像我定义的格式。但是由于某种原因,即使宽松设置为false,此调用返回Date对象为10/20/20128。

and I would expect the dateFormat.parse call to throw ParseException since the year I'm providing is 5 characters long instead of 4 like in the format I defined. But for some reason even with the lenient set to false this call returns a Date object of 10/20/20128.

为什么?对我来说没什么意义还有另一个设置让它更加严格吗?

Why is that? It doesn't make much sense to me. Is there another setting to make it even more strict?

推荐答案

20128是一个有效的一年,Java希望世界能够长存我猜,

20128 is a valid year and Java hopes the world to live that long I guess.


如果模式字母数超过2,则年份为
,无论数字如何的数字。

if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits.

参考

如果要验证日期是否为限制,您可以定义一个并检查 -

If you want to validate if a date is in limit, you can define one and check-

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date maxDate = sdf.parse("01/01/2099");  // This is the limit

if(someDate.after(maxDate)){            
    System.out.println("Invalid date");            
}

这篇关于为什么SimpleDateFormat(“MM / dd / yyyy”)将日期解析为10/20/20128?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆