私は、次の操作を行うための試みの後java.time.format.DateTimeParseException
を得る:LOCALDATE:MM-YYYYを解析
LocalDate.parse("09-2017" , DateTimeFormatter.ofPattern("MM-yyyy"))
間違っていますか? JavaにdateString形式をチェックするユーティリティはありますか?
私は、次の操作を行うための試みの後java.time.format.DateTimeParseException
を得る:LOCALDATE:MM-YYYYを解析
LocalDate.parse("09-2017" , DateTimeFormatter.ofPattern("MM-yyyy"))
間違っていますか? JavaにdateString形式をチェックするユーティリティはありますか?
LocalDate
は、作成する日、月、年が必要です。あなたの入力は月と年だけです。任意の日を選択し、解析されたオブジェクトに設定してLocalDate
を作成する必要があります。
あなたはjava.time.YearMonth
にそれを解析し、その日を選択することができ、次のいずれか
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM-yyyy");
YearMonth ym = YearMonth.parse("09-2017", fmt);
LocalDate dt = ym.atDay(1); // choose whatever day you want
それとも、その日のためにデフォルト値を定義するためにjava.time.temporal.ChronoField
でjava.time.format.DateTimeFormatterBuilder
を使用することができます。
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// month-year
.appendPattern("MM-yyyy")
// default value for day
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
// create formatter
.toFormatter();
LocalDate dt = LocalDate.parse("09-2017", fmt);
PS:入力が正しいかどうかを確認したい場合は、それを解析してYearMonth
で十分です(すでに解析された値が有効かどうかを確認しています)。
これはLOCALDATEオブジェクトを作成するための有効/十分な情報ではありませんが、その代わりに
System.out.println(LocalDate.parse("01-09-2017", DateTimeFormatter.ofPattern("dd-MM-yyyy")));
をするか、または任意の他にデイ情報を追加...
あなたのコードの失敗の原因であります方法