简体   繁体   English

未捕获日期格式异常

[英]Date format exception is not caught

public OrderDate(String date) throws IllegalDateFormatException {   
  SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yy");
  try {
    dateFormat.parse(date);
    this.date = date;
  } catch (ParseException e) {
    throw new IllegalDateFormatException("Date must have the following format: dd/mm/yy");
  }
}

If I use for example 32/05/12 - it doesn't throw an exception. 如果我使用例如32/05/12-它不会引发异常。

I also tried: Date givenDate = dateFormat.parse(date); 我也尝试过:给定Date givenDate = dateFormat.parse(date);

Need clarification. 需要澄清。

Update: 更新:

public OrderDate(String date) throws IllegalDateFormatException
{   
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yy");
    try 
    {
        dateFormat.setLenient(false);
        dateFormat.parse(date);
        this.date = date;
    }
    catch(ParseException e) 
    {
        throw new IllegalDateFormatException("Date must have the following"
                                                     + " format: dd/mm/yy");
    }
}

It catches the exception, if the date is 32/06/12! 如果日期是12/06/32,它将捕获异常! At the same time, there is no catch, if the date is 31/06/12. 同时,如果日期为2012年6月31日,则没有捕获。 But there are 30 days in June! 但是六月有30天!

By default, setLenient of SimpleDateFormat is true . 默认情况下, SimpleDateFormat setLenienttrue So, whenever you parse 32/05/12 , it is automatically converted to 01/06/12 . 因此,每当您解析32/05/12 ,它将自动转换为01/06/12 That why no exception is throws. 那就是为什么不抛出异常的原因。 If you need strict parsing than use setLenient(false) , it will throw Exception at above case. 如果需要严格解析而不是使用setLenient(false) ,则在上述情况下将抛出Exception Look at the docs . 看一下文档

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. 在严格分析的情况下,输入必须与该对象的格式匹配。

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

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