为什么SimpleDateFormat解析错误的日期? [英] Why does SimpleDateFormat parse incorrect date?

查看:114
本文介绍了为什么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.setL enient(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。您可能会使用 parse 的重载,它接受 ParsePosition ,然后在解析完成后检查当前的解析索引:

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时间 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天全站免登陆