乔达:如何获得两个日期之间的月份和日期
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 个月零天。
如果不受支持,documentation Period.getDays() 将 return0。我不确定为什么会不受支持,但我想提供一种不同的方法:使用 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);
州
Creates a period from the given interval endpoints using the standard
set of fields.
换句话说,相当于
Period period = new Period(startTime, endTime, PeriodType.standard());
PeriodType#standard()
方法returns一个PeriodType
支持周字段。
您的经期 2015 年 7 月 1 日至 2015 年 11 月 29 日,实际上是 4 个月零 28 天,其中 28 天转化为 4 周。所以你的 Period
对象实际上是 4 个月零 4 周。
如果您尝试在 2015 年 7 月 1 日至 2015 年 11 月 30 日 期间创建 Period
,您将有 4 个月零 4 周零 1 天。
相反,使用仅支持年、月和日字段的 PeriodType#yearMonthDay()
创建 Period
。
period = new Period(begin, end, PeriodType.yearMonthDay());
然后你会有一个 Period
4 个月零 28 天,因为它不支持周。
我想我在这里遗漏了一些微妙之处,因为我正在阅读的所有内容都说这应该有效。我需要获取 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 个月零天。
如果不受支持,documentation Period.getDays() 将 return0。我不确定为什么会不受支持,但我想提供一种不同的方法:使用 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);
州
Creates a period from the given interval endpoints using the standard set of fields.
换句话说,相当于
Period period = new Period(startTime, endTime, PeriodType.standard());
PeriodType#standard()
方法returns一个PeriodType
支持周字段。
您的经期 2015 年 7 月 1 日至 2015 年 11 月 29 日,实际上是 4 个月零 28 天,其中 28 天转化为 4 周。所以你的 Period
对象实际上是 4 个月零 4 周。
如果您尝试在 2015 年 7 月 1 日至 2015 年 11 月 30 日 期间创建 Period
,您将有 4 个月零 4 周零 1 天。
相反,使用仅支持年、月和日字段的 PeriodType#yearMonthDay()
创建 Period
。
period = new Period(begin, end, PeriodType.yearMonthDay());
然后你会有一个 Period
4 个月零 28 天,因为它不支持周。