使用
org.joda.time.Period
:
// fields used by the period - use only months and days
PeriodType fields = PeriodType.forFields(new DurationFieldType[] {
DurationFieldType.months(), DurationFieldType.days()
});
Period period = new Period(dateOfBirth, endDate)
// normalize to months and days
.normalizedStandard(fields);
需要进行规范化,因为周期通常会创建“1个月、2周和3天”之类的内容,而规范化会将其转换为“1个月和17天”。使用特定的
DurationFieldType
上述功能还可以自动将年转换为月。
然后您可以获得月数和天数:
int months = period.getMonths();
int days = period.getDays();
另一个细节是
DateTime
对象
Period
还将考虑时间(小时、分钟、秒),以了解一天是否已经过去。
如果您想忽略时间而只考虑日期(日、月和年),请不要忘记将它们转换为
LocalDate
:
// convert DateTime to LocalDate, so time is ignored
Period period = new Period(dateOfBirth.toLocalDate(), endDate.toLocalDate())
// normalize to months and days
.normalizedStandard(fields);