Display "negative" time periods with a Joda-TimeFormatter time period


I use joda-time (1.6.2) in the project, and one of the things I do is the difference between the predicted time and the actual time. Sometimes this difference is positive, sometimes negative. Although a suitable approach might be to use Durationrather than Period, use PeriodFormatterto display the result has led me to the question of the PeriodFormatterBuilder class. As an example:

DateTime d1 = new DateTime(2011, 6, 17, 13, 13, 5, 0) ;
DateTime d2 = new DateTime(2011, 6, 17, 10, 17, 3, 0) ;

Period negativePeriod = new Period(d1, d2);
Period positivePeriod = new Period(d2, d1);

PeriodFormatter pf = new PeriodFormatterBuilder()
    .minimumPrintedDigits(2)
    .appendHours()
    .appendSuffix(":")
    .rejectSignedValues(true) // Does this do anything?
    .appendMinutes()
    .appendSuffix(":")
    .appendSeconds()
    .toFormatter();

System.out.printf("Negative Period: %s\n", pf.print(negativePeriod));
System.out.printf("Positive Period: %s\n", pf.print(positivePeriod));

The result of this:

Negative Period: -02:-56:-02
Positive Period: 02:56:02

I understand that Periodeach component of its date and time is stored separately, but for me the expected behavior of the method .rejectSignedValues(true)for building Formattermeans only displaying the sign -only for the first element of the type:

Negative Period: -02:56:02

API, ? JodaStephen? -?

, , , , , Builder.

,
-Manuel

+3
2

Javadoc rejectSignedValues Reject signed values when parsing the next and following appended fields, .. , .

, , . : P-6D8H ( ).

+1

:

 Duration dToFormat = duration;
    if (duration.getStandardMinutes() < 0) {
        dToFormat = duration.minus(duration).minus(duration);
    }

    ...

    if (duration.getStandardMinutes() < 0) {
                return "-"+pf.print(p); // leading minus
            }

:

public static String durationToHHHmmFormat(Duration duration, String separator){
        if ( duration == null ) {
            return null;
        }

        Duration dToFormat = duration;
        if (duration.getStandardMinutes() < 0) {
            dToFormat = duration.minus(duration).minus(duration);
        }

        Period p = dToFormat.toPeriod();
        PeriodFormatter pf = new PeriodFormatterBuilder()
            .printZeroAlways()
            .minimumPrintedDigits(2) // gives the '01'
            .appendHours()
            .appendSeparator(separator)
            .appendMinutes()
            .toFormatter();

        if (duration.getStandardMinutes() < 0) {
            return "-"+pf.print(p); // leading minus
        }
        return pf.print(p);
    }
0

All Articles