簡體   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