繁体   English   中英

如何使SimpleDateFormat.parse()失败?

[英]How to make SimpleDateFormat.parse() fail hard?

当提供的日期字符串与给定格式100%不匹配时,我需要以下代码才能开始失败。

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
format.setLenient(false);
format.parse("09/10/20144");

出于某种原因,即使使用setLenient(false),此调用也会返回实际的09/10/20144日期。 我尝试将“new ParsePosition(0)”传递给解析调用但这根本没有用,因为日期仍然以09/10/20144的形式返回。 我需要从确切的日期格式中的任何例外来努力失败。 这样做有什么好办法吗?

您给SDF的字符串仅通知格式化程序有关输入部分的顺序和类型(每个字段的间隔信息​​量是有限的,因为他应用了一些计算使其“有意义”)。

要实现您的目标,您可以使用正则表达式进行初始检查。 在你的情况下:

String input = "09/10/20144";
if (input == null || !input.matches("[01]\\d/[0123]\\d/[12]\\d{3}")) {
    throw new IllegalArgumentException("Invalid value or format");
} else {
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
    format.setLenient(false);
    format.parse(input);
}

以上正则表达式检查:

  • 月份有2位数,其中第一位是0或1
  • 这一天有2位数,第一位是{0,1,2,3}之一
  • 年份有4位数,第一位是1位或2位。

有关Java 中正则表达式的更多信息: http//docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

这是一种方法,虽然它有点奇怪:

public static Date parseDate(String input) {
    final String format = "MM/dd/yyyy";
    if (input.length != format.length) { //Check the length, helps to avoid the cases mentioned earlier.
        throw new ParseException("Lengths do not match", 0);
    }
    SimpleDateFormat format = new SimpleDateFormat(format);
    format.setLenient(false);
    return format.parse(input);
}

(这就是我之前在评论中所说的)

暂无
暂无

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

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