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

≡放荡痞女 提交于 2019-12-07 06:13:47

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/18489123/how-can-i-make-joda-datetime-parser-to-only-accept-strings-of-form-yyyymmdd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!