1

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());
 } 
josete
  • 357
  • 1
  • 3
  • 15
  • You realize your dates are actually *June* 20th to *July* 19th, right? Just as a first problem... – Jon Skeet May 20 '11 at 16:53
  • Sure, 1 day less than a month. Actual data is irrelevant .. i just wanted to reflect the 1 month -1 day fact. – josete May 23 '11 at 15:15

1 Answers1

3

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);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194