1

我正在使用 joda-time 来获取两个日期之间的一些时间/日期组件。( http://joda-time.sourceforge.net )

当我将 PeriodTypes 用作standard()orday()时,一切正常。但是当我使用时,PeriodType.forFields(...)我得到了一个例外:

所以,这有效:

Period p = new Period(new DateTime(startDate.getTime()), new DateTime(endDate.getTime()), PeriodType.days()).normalizedStandard(PeriodType.days());
return p.getDays();

这会引发异常:

Period p = new Period(new DateTime(startDate.getTime()), new DateTime(endDate.getTime()), PeriodType.forFields(new DurationFieldType[]{DurationFieldType.months(), DurationFieldType.weeks()})).normalizedStandard(PeriodType.forFields(new DurationFieldType[]{DurationFieldType.months(), DurationFieldType.weeks()}));
return p.getMonths();

任何想法我做错了什么?非常感谢任何帮助。

例外:

10-17 14:35:50.999:E/AndroidRuntime(1350):java.lang.UnsupportedOperationException:不支持字段 10-17 14:35:50.999:E/AndroidRuntime(1350):在 org.joda.time.PeriodType .setIndexedField(PeriodType.java:690) 10-17 14:35:50.999: E/AndroidRuntime(1350): 在 org.joda.time.Period.withYears(Period.java:896) 10-17 14:35:50.999 : E/AndroidRuntime(1350): 在 org.joda.time.Period.normalizedStandard(Period.java:1630)

编辑:

我很确定这是一个错误。我测试了更多组合,似乎没有年份的非标准 PeriodTypes 存在问题。例如:

这有效:

Period p = new Period(new DateTime(startDate.getTime()), new DateTime(endDate.getTime()), PeriodType.standard()).normalizedStandard(PeriodType.standard());
return p.getMonths();

如果我删除年份 PeriodType , withYearsRemoved() 我会得到一个例外:

Period p = new Period(new DateTime(startDate.getTime()), new DateTime(endDate.getTime()), PeriodType.standard().withYearsRemoved()).normalizedStandard(PeriodType.standard().withYearsRemoved());
return p.getMonths();
4

1 回答 1

1

这意味着startDate和之间的差异大于endDate年份,因此normalized standard无法计算。

Period::normalizedStandard

如果期间包含年或月,则月将被规范化为 0 到 11 之间。天和以下字段将根据需要进行规范化,但这不会溢出到月字段。因此,1 年 15 个月的期间将正常化为 2 年 3 个月。但是 1 个月 40 天的期间将保持为 1 个月 40 天。

因此,如果差异超过 1 年,则不能使用normalizedStandard withYearsRemoved.

例子:

  DateTime startDate = new DateTime().minusYears(10);
  DateTime endDate = new DateTime();
  Period p = new Period(startDate, endDate, PeriodType.standard().withYearsRemoved())
     .normalizedStandard(PeriodType.standard().withYearsRemoved());
  p.getMonths(); // throw exception, difference is 10 years!  

  DateTime startDate = new DateTime().minusMonths(10);
  DateTime endDate = new DateTime();
  Period p = new Period(startDate, endDate, PeriodType.standard().withYearsRemoved())
     .normalizedStandard(PeriodType.standard().withYearsRemoved());
  p.getMonths(); // return 10, difference is less then 1 year  

  DateTime startDate = new DateTime().minusYears(10);
  DateTime endDate = new DateTime();
  Period p = new Period(startDate, endDate, PeriodType.standard().withYearsRemoved());
  p.getMonths(); // return 120, standart isn't normalized
于 2013-10-18T08:55:54.027 回答