简体   繁体   English

SimpleDateFormat.parse未检测到不正确的日期

[英]SimpleDateFormat.parse not detecting incorrect date

Been experimenting with SimpleDateFormat. 正在尝试SimpleDateFormat。 One thing I do not understand : why does the following returns ok ? 有一件事我不明白:为什么下面的返回ok

String pattern = "MM/dd/yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);

String input = "2023/03/22";
Date d = null;

try {
    d = format.parse(input);
} catch (ParseException e) {
    System.out.println("nok");
}

System.out.println("ok");

Date returned is absurd too : Fri Jul 03 00:00:00 CET 190 返回的日期也很荒谬: Fri Jul 03 00:00:00 CET 190

Any explanation is greatly appreciated! 任何解释,不胜感激!

Let's spell it out for those readers who want it all in the answer: 让我们为那些想要答案中所有内容的读者说明一下:

format.setLenient(false) is what you need. format.setLenient(false)是您所需要的。

Here's how you might do it. 这是您可能的操作方式。 I agree with AxelH: You should be using JDK8, java.time package and LocalTime : 我同意AxelH:您应该使用JDK8, java.time包和LocalTime

import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class DateFormatTest {

    @Test(expected = ParseException.class)
    public void testSetLenient_IncorrectDateInput() throws ParseException {
        // setup
        String input = "2023/03/22";
        String pattern = "MM/dd/yyyy";
        DateFormat format = new SimpleDateFormat(pattern);
        format.setLenient(false);
        // exercise and assert
        format.parse(input);
    }
}

Any explanation is greatly appreciated! 任何解释,不胜感激!

here we go: the explanation is simple: 我们开始:解释很简单:

this format "MM/dd/yyyy" is pretty simple about how is what, the object is expecting a month day year information to be parsed. 该格式“ MM / dd / yyyy”非常简单,即对象是如何解析一个月日年份信息。

so you are giving this "2023/03/22" , then the 1st this is wrong here is that the moth (which should be between 1 and 12) is holding the value 2023, this is interpreted by the parser as the month 12 + 2011 extra months after that. 因此,您给出的是“ 2023/03/22” ,那么这里的第一个错误是蛾(应在1到12之间)持有值2023,解析器将其解释为月份12 +在那之后的2011年。

day 03 is ok, and year 22 means exactly that, the year 22 After Christos birth. 第三天还可以,而22年恰好意味着克里斯托斯出生后的22年。

so your resulting date is 因此,您得出的日期是

the valid data plus the weird offset, ie 有效数据加上怪异的偏移量,即

12/03/0022 + 2011 months. 12/03/0022 + 2011个月。

now 2011 months is the same as: 167 years and 7 months so we do the math: 现在的2011个月等于:167年零7个月,所以我们做一下数学运算:

12 03 of the year 22 plus 167 years and 7 months... then you get 每年12月3日22加上167年零7个月...

Fri Jul 03 00:00:00 CET 190 星期五七月03 00:00:00欧洲中部时间190


the solution: 解决方案:

format.setLenient(boolean);

check the doc to see what exception will be thrown in such case.... 检查文档以查看在这种情况下将引发什么异常...。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM