I would like to use Joda-Time to parse dates in the format yyyyMMdd (so the date should have eight digits). I defined my date formatter as follows
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd").withZoneUTC();
// a valid eight-digit date
String dateValid = "20130814";
DateTime dateJoda = formatter.parseDateTime(dateValid);
System.out.println(dateJoda.toString());
// an invalid seven digit date
String dateInvalid = "2013081";
dateJoda = formatter.parseDateTime(dateInvalid);
System.out.println(dateJoda.toString());
I expected to see an exception when parsing the second invalid date. However the output of the code is
2013-08-14T00:00:00.000Z
2013-08-01T00:00:00.000Z
Why does the Joda parser accept the invalid date with only 7 digits? How do I have to change my formatter to not accept any dates which don't have exactly 8 digits?
The only option I know of is to create your own DateTimeFormatter using DateTimeFormatterBuilder and use fixed decimals for each field.
In your case it would be:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendFixedDecimal(DateTimeFieldType.year(),4)
.appendFixedDecimal(DateTimeFieldType.monthOfYear(),2)
.appendFixedDecimal(DateTimeFieldType.dayOfMonth(),2)
.toFormatter()
.withZoneUTC();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With