我需要获取两个 DateTime
对象之间的月数,然后获取剩余的天数。
以下是我获取月份之间的方法:
月份monthsBetween = Months.monthsBetween(dateOfBirth,endDate);
我不确定如何找出下个月还剩多少天。我尝试过以下方法:
int offset = Days.daysBetween(dateOfBirth,endDate)
.minus(monthsBetween.get(DurationFieldType.days())).getDays();
但这并没有达到预期的效果。
最佳答案
使用 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);
关于java - 两个 Joda DateTime 之间的差异(以月为单位)和剩余天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48885684/