我试图在 yyyy
部分之前使用带前导“+”的 jodatime 解析日期字符串。本以为会抛出错误,但实际上并没有抛出错误。我得到的输出没有任何意义:
System.out.println(DateTimeFormat.forPattern("yyyyMMdd").parseDateTime("20130101"));
// 2013-01-01T00:00:00.000+05:30 (Expected) (case 1)
System.out.println(DateTimeFormat.forPattern("yyyyMMdd").parseDateTime("+20130101"));
// 20130-10-01T00:00:00.000+05:30 (??? Notice that month changed to 10 also) (case 2)
System.out.println(DateTimeFormat.forPattern("MMyyyydd").parseDateTime("01+201301"));
// 20130-01-01T00:00:00.000+05:30 (??? At least month is fine this time) (case 3)
System.out.println(DateTimeFormat.forPattern("MM-yyyy-dd").parseDateTime("01-+2013-01"));
// 2013-01-01T00:00:00.000+05:30 (I expected an error, but this parsed correctly) (case 4)
谁能解释为什么会这样?我希望出现异常,这意味着不允许使用“+”符号,或者它应该将 +2013 简单地解释为 2013,这似乎是最后一种情况。但是,案例 2 和案例 3 中的 20130 以及案例 2 中的月份 = 10 是怎么回事?
最佳答案
如果你想在 +
标志上抛出异常,你可以使用 DateTimeFormatterBuilder ,它更灵活。
例如。对于格式 yyyyMMdd
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendFixedDecimal(DateTimeFieldType.year(), 4)
.appendMonthOfYear(2)
.appendDayOfMonth(2)
.toFormatter();
dtf.parseDateTime("19990101"); - parsed correctly
dtf.parseDateTime("-19990101"); - throw exception
dtf.parseDateTime("+19990101"); - throw exception
这种模式也已经存在于标准模式中:
ISODateTimeFormat::basicDate()
编辑
但是在使用 appendFixedSignedDecimal 的情况下会出现奇怪的行为方法:
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendFixedSignedDecimal(DateTimeFieldType.year(), 4)
.appendMonthOfYear(2)
.appendDayOfMonth(2)
.toFormatter();
dtf.parseDateTime("19990101"); - parsed correctly
dtf.parseDateTime("-19990101"); - parsed correctly (negative years)
dtf.parseDateTime("+19990101"); - throw exception (???)
我认为这是 Joda 库中的问题,因为
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendFixedSignedDecimal(DateTimeFieldType.year(), 4)
.toFormatter();
按预期工作
dtf.parseDateTime("1999"); - parsed correctly
dtf.parseDateTime("-1999"); - parsed correctly (negative years)
dtf.parseDateTime("+1999"); - parsed correctly
(此案例存在于 joda 库的 Unit Tests 中)
关于java - jodatime 在解析某些日期格式时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19910018/