6

I have a method like this:

public static String getFormattedDateDifference(DateTime startDate, DateTime endDate) {
        Period p = new Period(startDate, endDate);
        return PeriodFormat.getDefault().print(p);
    }

I'd like to chop off the seconds and milliseconds from printing. How can I do that?

LuxuryMode
  • 33,401
  • 34
  • 117
  • 188
  • Use your own formatter instead of the default? See [this SO question for possible guidance](http://stackoverflow.com/questions/4585883/understanding-joda-time-periodformatter). – Dave Newton Sep 22 '11 at 17:54

1 Answers1

10

If you only want it down to minutes, why not just specify the right period type to start with?

private static final PeriodType PERIOD_TO_MINUTES = 
     PeriodType.standard().withSecondsRemoved().withMillisRemoved();

public static String getFormattedDateDifference(DateTime startDate,
                                                DateTime endDate) {

    Period p = new Period(startDate, endDate, PERIOD_TO_MINUTES);
    return PeriodFormat.getDefault().print(p);
}

I expect that to format in the way you want.

Note that if these are really meant to be dates, you should probably use PeriodType.yearMonthDay() and specify the values as LocalDate. DateTime should be used for date and time values, not just dates.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194