Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make Joda DateTime parser to only accept strings of form yyyyMMdd?

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?

like image 755
asmaier Avatar asked Aug 28 '13 13:08

asmaier


1 Answers

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();
like image 98
soulcheck Avatar answered Nov 14 '22 23:11

soulcheck