如何防止SimpleDateFormat解析错误的格式化日期? [英] How to prevent SimpleDateFormat to parse wrong formatted dates?

查看:178
本文介绍了如何防止SimpleDateFormat解析错误的格式化日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 SimpleDateFormat 将字符串解析为 Date 对象,我想知道为什么结果不是我期望的。

I use SimpleDateFormat to parse strings to Date objects and I wonder why the results are not what I expect.

例如:

DateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");

Date date = yyyyMMdd.parse("20100725");
System.out.println(date);

按预期工作并输出

Sun Jul 25 00:00:00 CEST 2010

但是

Date date = yyyyMMdd.parse("2010-07-25");
System.out.println(date);

也可以工作和输出

Mon Dec 07 00:00:00 CET 2009

我期望code> ParseException ,但似乎 SimpleDateFormat 解释了月份部分 -07 ,而日期部分 -25 为负数。首先,我不知道12月7日如何。因此,我尝试了另一个值:

I expected a ParseException, but it seems that SimpleDateFormat interpretes the month part -07 and the day part -25 as a negative number. First I couldn't figure out how it comes to 7th of december. So I tried another value:

Date date = yyyyMMdd.parse("2010-7-25");
System.out.println(date);

出局

Sun Apr 05 00:00:00 CEST 2009

不知何故地从2010年 年减去了 7 个月(可能是5月1日)和 25 天,因此结果为2009年4月5日。

So it seems that it somehow subtracts 7 month from the year 2010 which whould be 1th of may, and 25 days so the result is 5th of april 2009.

使用模式 yyyyMMdd 在服务实现中,某些客户端意外地将日期发送为 yyyy-MM-dd 。您不会例外。相反,您将获得完全不同的日期。我想这不是您期望的。

Image that you use the pattern yyyyMMdd in an service implementation and some client accidentially sends the date as yyyy-MM-dd. You will not get an exception. Instead you will get totally different dates. I guess this is not what you expect.

例如

String clientData = "2010-05-23";

DateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
Date parsedDate = yyyyMMdd.parse(clientData);

System.out.println("Client  : " + clientData);
System.out.println("Service : " + yyyyMMdd.format(parsedDate));

我想念东西吗?

如何防止 SimpleDateFormat 解析错误的日期?

How do I prevent SimpleDateFormat to parse 'wrong' dates?

我可以使用先检查正则表达式,但是还有更好的方法吗?

Sure I can use a regular expression to check first, but is there a better way?

推荐答案

使用 SimpleDateFormat.setLenient( false); 获取异常。否则,它将尝试尽可能地解析输入,这通常是错误的。

Use SimpleDateFormat.setLenient(false); to get an exception. Otherwise it will try to parse the input as best as it can, which is usually wrong.

由于某种原因,他们决定默认情况下宽大处理为真,但这就是难怪

For some reason they decided that leniency should be true by default, but that is hardly a surprise.


指定日期/时间解析是否宽松。通过
宽大的解析,解析器可以使用启发式方法来解释与该对象的格式不完全匹配的输入
。通过严格的
解析,输入必须匹配该对象的格式。

Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

这篇关于如何防止SimpleDateFormat解析错误的格式化日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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