LoginSignup
34
35

More than 5 years have passed since last update.

日付が正しいかどうかをチェックする

Last updated at Posted at 2012-11-28

文字列で渡された日付が、"2012/09/32"といったように不正な値かどうかを確認する方法。

SimpleDateFormat

DateFormat format=new SimpleDateFormat("yyyy-MM-dd");

try {
    format.parse("2012-09-01");//成功
    format.parse("2012-09-32");//成功

    format.setLenient(false);
    format.parse("2012-09-32");//Exception
} catch (ParseException e) {
    //失敗時の処理…
}

SimpleDateFormatはデフォルトでは書式フォーマットのみをチェックするので、32日のような不正値で例外が投げられない。
不正な日付をチェックしたい場合は、setLenientでfalseをセットする。

Commons DateUtils

commons-langに含まれているDateUtilsを使う場合は以下のように。

try {
    DateUtils.parseDateStrictly("2012-09-01", new String[] {"yyyy-MM-dd"});
    DateUtils.parseDateStrictly("2012-09-32", new String[] {"yyyy-MM-dd"});//Exception
} catch (ParseException e) {
    // エラー処理...
}

これも内部的にはSimpleDateFormatを使った実装。こちらは書式フォーマットをString配列で複数指定できるようになっている。

34
35
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
35