Reputation: 267
I need to figure out how to calculate how many days there are between 2 dates using joda time 1.2 (no I can not use a newer version). So the Days class doesn't exist yet.
I can do this for the weeks and days
(period.getWeeks()*7 + period.getDays());
But when it comes to months they all have a different number of days in them so I can't do period.getMonths()*30.
edit: I can also do
(today.getDayOfYear() - oldDate.getDayOfYear());
but then there's the problem when the dates are in different years
Thanks
Upvotes: 0
Views: 1041
Reputation: 10974
Take a look at the Joda Time source code. The daysBetween
method of Days is defined as:
public static Days daysBetween(ReadableInstant start, ReadableInstant end) {
int amount = BaseSingleFieldPeriod.between(start, end, DurationFieldType.days());
return Days.days(amount);
}
BaseSingleFieldPeriod
, like Days, is not available in Joda Time 1.2 but, looking at its source classes available in 1.2 start to appear:
protected static int between(ReadableInstant start, ReadableInstant end, DurationFieldType field) {
if (start == null || end == null) {
throw new IllegalArgumentException("ReadableInstant objects must not be null");
}
Chronology chrono = DateTimeUtils.getInstantChronology(start);
int amount = field.getField(chrono).getDifference(end.getMillis(), start.getMillis());
return amount;
}
All of those classes and methods are available in Joda Time 1.2 so computing days between two instances would be something like:
public static int daysBetween(ReadableInstant oldDate, ReadableInstant today) {
Chronology chrono = DateTimeUtils.getInstantChronology(oldDate);
int amount = DurationFieldType.days().getField(chrono).getDifference(today.getMillis(), oldDate.getMillis());
return amount;
}
Upvotes: 1