为什么 SimpleDateFormat 解析不正确的日期? [英] Why does SimpleDateFormat parse incorrect date?

查看:55
本文介绍了为什么 SimpleDateFormat 解析不正确的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字符串格式的日期,我想将其解析为实用程序日期.

I have date in string format and I want to parse that into util date.

var date ="03/11/2013"

我将其解析为:

new SimpleDateFormat("MM/dd/yyyy").parse(date)

但奇怪的是,如果我通过03-08-201309 hjhkjhk"或03-88-2013"​​或43-88-201378",它不会抛出错误,它会解析它.

But the strange thing is that, if I am passing "03-08-201309 hjhkjhk" or "03-88-2013" or 43-88-201378", it does not throw error , it parses it.

为此,我必须编写正则表达式模式来检查日期输入是否正确.但为什么会这样??

For this now, I have to write regex pattern for checking whetehr input of date is correct or not. but why is it so ??

代码:

scala> val date="03/88/201309 hjhkjhk"
date: java.lang.String = 03/88/201309 hjhkjhk

scala> new SimpleDateFormat("MM/dd/yyyy").parse(date)
res5: java.util.Date = Mon May 27 00:00:00 IST 201309

推荐答案

你应该使用 DateFormat.setLenient(false):

SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
df.setLenient(false);
df.parse("03/88/2013"); // Throws an exception

我不确定它会捕捉一切你想要的 - 我似乎记得即使使用 setLenient(false) 它也比你想象的要宽松 - 但它例如,应该捕获无效的月份数字.

I'm not sure that will catch everything you want - I seem to remember that even with setLenient(false) it's more lenient than you might expect - but it should catch invalid month numbers for example.

我认为它不会捕获尾随文本,例如03/01/2013 sjsjsj".您可以潜在地使用接受 ParsePositionparse 的重载,然后在解析完成后检查当前的解析索引:

I don't think it will catch trailing text, e.g. "03/01/2013 sjsjsj". You could potentially use the overload of parse which accepts a ParsePosition, then check the current parse index after parsing has completed:

ParsePosition position = new ParsePosition(0);
Date date = dateFormat.parse(text, position);
if (position.getIndex() != text.length()) {
    // Throw an exception or whatever else you want to do
}

您还应该查看 Joda Time API,它很可能允许更严格的解释 - 而且是无论如何,一个更清晰的日期/时间 API.

You should also look at the Joda Time API which may well allow for a stricter interpretation - and is a generally cleaner date/time API anyway.

这篇关于为什么 SimpleDateFormat 解析不正确的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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