Java 两个Joda DateTime(以月为单位)和剩余天数之间的差异
我需要获取两个Java 两个Joda DateTime(以月为单位)和剩余天数之间的差异,java,android,jodatime,period,date-difference,Java,Android,Jodatime,Period,Date Difference,我需要获取两个DateTime对象之间的月数,然后获取剩余天数 以下是我如何计算以下月份之间的月份: monthsMonthsBetween=Months.monthsBetween(出生日期,结束日期) 我不知道怎样才能知道下个月还剩多少天。我尝试了以下方法: int offset = Days.daysBetween(dateOfBirth,endDate) .minus(monthsBetween.get(DurationFieldType.days())).g
DateTime
对象之间的月数,然后获取剩余天数
以下是我如何计算以下月份之间的月份:
monthsMonthsBetween=Months.monthsBetween(出生日期,结束日期)代码>
我不知道怎样才能知道下个月还剩多少天。我尝试了以下方法:
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/<代码>对象时,期也会考虑时间(小时、分钟、秒)来知道一天是否已经过去。
如果你想忽略时间,只考虑日期(日期、月份和年份),不要忘记将它们转换成<代码> LoalDeals<代码>:
// convert DateTime to LocalDate, so time is ignored
Period period = new Period(dateOfBirth.toLocalDate(), endDate.toLocalDate())
// normalize to months and days
.normalizedStandard(fields);