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.
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:
It’s important to understand the difference between a
Durationwhich is “a certain number of milliseconds, which can be fetched according to different units” and aPeriodwhich 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.