[英]Difference Between Two Joda DateTime In Months and Left Over Days
我需要获取两个DateTime
对象之间的月数,然后获取剩余的天数。
这是我得到两个月之间的时间的方法:
Months 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.