[英]How to calculate No of Years, Months and days between two dates using Joda-Time
[英]Joda: how to get months and days between two dates
我想我在這里缺少一些微妙之處,因為我正在閱讀的所有內容都表明這應該可行。 我需要獲取Android中兩個日期之間的月份和日期。 也就是說,多少個月加上任何其他天數。 我需要此作為數字輸出,而不是打印的字符串。 這是我使用Joda做的事情:
void method(DateTime begin, DateTime end) {
Period period = Period period = new Period(begin, end);
final int months = period.getMonths();
final int additionalDays = period.getDays();
問題是additionalDays
始終為零。 例如,2015年7月1日至2015年11月29日應為4個月29天,但我得到4個月0天。
如果不受支持,從文檔 Period.getDays()將返回0。 我不確定為什么不支持這種方法,但是我想提供一種不同的方法:使用Days
和Months
類以及它們的monthsBetween()
和daysBetween()
方法。 請注意,您還必須減去兩個月之間的月份:
// Get months
int months = Months.monthsBetween(begin, end).getMonths();
// Subtract this number of months from the end date so we can calculate days
DateTime newEnd = end.minusMonths(months);
// Get days
int days = Days.daysBetween(begin, newEnd).getDays();
如果你沒有在中間瓶坯這個減法,你會得到不正確的結果,你會得到所有天。
您使用的Period
構造函數的Javadoc
new Period(begin, end);
狀態
使用標准字段集從給定間隔端點創建一個周期。
換句話說,它相當於
Period period = new Period(startTime, endTime, PeriodType.standard());
PeriodType#standard()
方法返回一個支持PeriodType
字段的PeriodType
。
您的期限為2015年7月1日至2015年11月29日 ,實際上是4個月28天,其中28天變成了4周。 因此,您的Period
對象實際上是4個月零4周。
如果你曾試圖創造一個Period
從2015年7月1日至十一月30日2015年 ,你有4個月,4周,1天。
而是使用PeriodType#yearMonthDay()
創建一個Period
,該PeriodType#yearMonthDay()
僅支持年,月和日字段。
period = new Period(begin, end, PeriodType.yearMonthDay());
那么您的Period
為4個月28天,因為它不支持數周。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.