如何让Joda DateTime解析器只接受yyyyMMdd形式的字符串? [英] How can I make Joda DateTime parser to only accept strings of form yyyyMMdd?

查看:623
本文介绍了如何让Joda DateTime解析器只接受yyyyMMdd形式的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Joda-Time以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

为什么Joda解析器只接受7位数的无效日期?如何更改格式化程序以不接受任何没有8位数字的日期?

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?

推荐答案

我所知道的唯一选择是使用 DateTimeFormatterBuilder 并为每个字段使用固定小数。

The only option I know of is to create your own DateTimeFormatter using DateTimeFormatterBuilder and use fixed decimals for each field.

在你的情况下它将是:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendFixedDecimal(DateTimeFieldType.year(),4)
    .appendFixedDecimal(DateTimeFieldType.monthOfYear(),2)
    .appendFixedDecimal(DateTimeFieldType.dayOfMonth(),2)
    .toFormatter()
    .withZoneUTC();

这篇关于如何让Joda DateTime解析器只接受yyyyMMdd形式的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆