user1186512
user1186512

Reputation: 1

Getting JODA Duration to work

The following code does not print the days correctly, I need to print out days and minutes as well.

Duration duration = new Duration(1328223198241L - 1326308781131L);
Period p2 = new Period(duration.getMillis());
System.out.println(p2.getDays()); // prints 0, should print 22 days
System.out.println(p2.getHours()); // prints  531 which is expected.

Upvotes: 0

Views: 191

Answers (3)

Dark Star1
Dark Star1

Reputation: 7383

Does the following not suffice: System.out.println(duration.getStandardDays());

Upvotes: 0

Jasonw
Jasonw

Reputation: 5064

According to the javadoc, "Only precise fields in the period type will be used. For the standard period type this is the time fields only. Thus the year, month, week and day fields will not be populated." thus you are getting zero.

Consider this alternative.

Duration duration = new Duration(1328223198241L - 1326308781131L);      
Period p2 = new Period(duration.getMillis());
System.out.println(p2.getHours()); // prints  531 which is expected.
System.out.println(p2.toStandardDays().getDays()); // prints 22 days

Upvotes: 3

jtoberon
jtoberon

Reputation: 9016

This behavior is explained in the javadocs: "duration is larger than one day then all the remaining duration will be stored in the largest available precise field, hours in this case."

If you explain what you're trying to do, as opposed to how you're trying to do it, then I'm sure we'll be able to help out. For example, to find what I think you're trying to get from p2.getDays():

Days.daysBetween(dateTime1, dateTime2).getDays()

Upvotes: 0

Related Questions