TGM
TGM

Reputation: 1679

Joda Time minutes in a duration or interval

I have this simple code:

DateTime date = new DateTime(dateValue);
DateTime currentDate = new DateTime(System.currentTimeMillis());

System.out.println("date: " + date.toString());
System.out.println("currentDate: " + currentDate.toString());

Period period = new Period(currentDate, date);
System.out.println("PERIOD MINUTES: " + period.getMinutes());
System.out.println("PERIOD DAYS: " + period.getDays());

Duration duration = new Duration(currentDate, date);
System.out.println("DURATION MINUTES: " + duration.getStandardMinutes());
System.out.println("DURATION DAYS: " + duration.getStandardDays());

I'm trying to simply find out the number of days and minutes between two random dates.

This is the output for this piece of code:

date: 2012-02-09T00:00:00.000+02:00
currentDate: 2012-02-09T18:15:40.739+02:00
PERIOD MINUTES: -15
PERIOD DAYS: 0
DURATION MINUTES: -1095
DURATION DAYS: 0

I'm guessing that I'm doing something wrong, I just cannot see what.

Upvotes: 5

Views: 6267

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500515

The problem is that you're not specifying the period type in the period constructor - so it's using the default of "years, months, weeks, days, hours, minutes, seconds and millis". You're only seeing 15 minutes because you're not asking for hours, which would return -18.

If you only want days and minutes, you should specify that:

PeriodType type = PeriodType.forFields(new DurationFieldType[] {
                                           DurationFieldType.days(),
                                           DurationFieldType.minutes()
                                       });

Period period = new Period(currentDate, date, type);
// Now you'll just have minutes and days

It's important to understand the difference between a Duration which is "a certain number of milliseconds, which can be fetched according to different units" and a Period which is effectively a mapping from a set of field types (minutes, months, days etc) to values. There isn't one single time value in a period - it's a collection of values.

Upvotes: 13

jbranchaud
jbranchaud

Reputation: 6087

It looks like it is working just fine, all you need to do to get positive values is swap around date and currentDate:

Period period = new Period(date, currentDate);

Upvotes: 3

Related Questions