Search code examples
javaparsingprintingjodatimeperiod

Error in Printing Period with JodaTime?


I've have a problem trying to print a given period between two dates.

Let me show you the details, and then i'll put the code :

Date a = May, 20th , Date b = June, 19th

Period in between should be 30 days.(or 29, doesn't matter)

But given the code i have, it says it's only 1 day.

Can you help me with this, please ? What i'd like is to get the whole period in between : 29 days.

Thanks.

public static void main(String args[]) {

  Calendar calA = Calendar.getInstance();
  calA.set(Calendar.MONTH, 5);
  calA.set(Calendar.DAY_OF_MONTH, 20);

  Calendar calB = Calendar.getInstance();
  calB.set(Calendar.MONTH, 6);
  calB.set(Calendar.DAY_OF_MONTH, 19);

  DateTime da = new DateTime(calA.getTime());
  DateTime db = new DateTime(calB.getTime());
  Period p = new Period(da,db);
  System.out.println(printPeriod(p));

}

 private static String printPeriod(Period period) {

   PeriodFormatter monthDaysHours = new PeriodFormatterBuilder()
    .appendMonths()
    .appendSuffix(" month"," months")
    .appendSeparator(",")
    .appendDays()
    .appendSuffix(" day", " days")
    .appendSeparator(",")
    .appendHours()
    .appendSuffix(" hour"," hours")
    .toFormatter();

 return monthDaysHours.print(period.normalizeStandardPeriodType());
 } 

Solution

  • The period has been created as "4 weeks and 1 day" - but you're not printing out the weeks.

    Assuming you want year/month/day/time, change your Period constructor call to:

    Period p = new Period(da, db, PeriodType.yearMonthDayTime());
    

    and then get rid of the call to normalizeStandard() (I couldn't actually find a method called normalizeStandardPeriodType(); I'm assuming that was a typo.)

    Of course, that will ignore any years in the period. You could potentially use:

    PeriodType pt = PeriodType.yearMonthDayTime().withYearsRemoved();
    Period p = new Period(da, db, pt);