5

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?

asmaier
  • 11,132
  • 11
  • 76
  • 103

1 Answers1

9

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();
soulcheck
  • 36,297
  • 6
  • 91
  • 90
  • Thank you, this seems to work. But don't forget `.withZoneUTC()` – asmaier Aug 28 '13 at 14:06
  • 4
    I found another solution: `DateTimeFormatter formatter = ISODateTimeFormat.basicDate().withZoneUTC();` . It works, because the ISO basic date is equal to yyyyMMdd . But this is in general less flexible than constructing a formatter using `.appendFixedDecimal()`. – asmaier Aug 28 '13 at 14:44
  • @soulcheck worth appending asmaiers suggestion to your answer? – vikingsteve Aug 29 '13 at 08:10