Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda Time minutes in a duration or interval

Tags:

java

date

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.

like image 737
TGM Avatar asked Feb 09 '12 16:02

TGM


2 Answers

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.

like image 175
Jon Skeet Avatar answered Sep 24 '22 07:09

Jon Skeet


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);
like image 41
jbranchaud Avatar answered Sep 23 '22 07:09

jbranchaud