Search code examples
javadatejodatimesubtraction

Removing '-' from negative Joda time Periods


I have a question regarding subtracting Joda DateTimes, and I use Period to get number of dates, hours, minutes and seconds between the two.

Output example : 2 days 11h 23min 05sec

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime firstDate = formatter.parseDateTime(firstStringDateValue);
DateTime secondDate = formatter.parseDateTime(secondStringDateValue);

DurationFieldType[] types = {DurationFieldType.days(), 
                             DurationFieldType.hours(), 
                             DurationFieldType.minutes(), 
                             DurationFieldType.seconds()};

Period period = new Period(firstDate, secondDate, PeriodType.forFields(types));

PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
            .minimumPrintedDigits(2)
            .appendDays().appendSuffix(" Day", " Days").appendSeparator(" ")
            .appendHours().appendSuffix("h").appendSeparator(" ")
            .appendMinutes().appendSuffix("min").appendSeparator(" ")
            .appendSeconds().appendSuffix("sec")
            .toFormatter();

String result = periodFormatter.print(period);

The problem is when the start the date is greater than the end date.

The result is something like this : -2 days -11h -23min -05sec

So I was wondering is there a way to make it look like this : - 2 days 11h 23min 05sec, with only one '-' in front of the whole thing. But using Joda related functions.

Or at least a method to tell me if the Period is negative.

I can do this using string manipulation but it seems a bit too manual.

Thank you.


Solution

  • What you need is comparing two date.

    There are isAfter and isBefore methods that compare dates by millis (ignoring time zone).

    firstDate.isBefore(secondDate)
    firstDate.isAfter(secondDate)
    

    Now, you can set parameters in the correct order.
    Then, add the leading minus if needed.