AppiDevo
AppiDevo

Reputation: 3235

jodatime - PeriodFormatter: suffix only for day/days

I need only to show suffix for day/days, how can I achieve that? It doesn't work:

java.lang.IllegalStateException: No field to apply suffix to..

    private PeriodFormatter getDayTextFormatter() {
        return new PeriodFormatterBuilder()
                .printZeroNever()
                .appendSuffix("day", "days")
                .toFormatter();
    }

Upvotes: 2

Views: 209

Answers (1)

user7605325
user7605325

Reputation:

I don't think it's possible. According to JodaTime's javadoc, the appendSuffix method will throw an exception if there's no field to append the suffix:

Throws: IllegalStateException - if no field exists to append to

So I believe JodaTime can't help you this time. Although, you could do something like this:

private String suffix(Period p) {
    int days = p.getDays();
    if (days <= 0) {
        return "";
    }

    return days == 1 ? "day" : "days";
}

With this code, the following:

System.out.println(suffix(Period.days(1)));
System.out.println(suffix(Period.days(2)));
System.out.println(suffix(new Period()));

produces the output:

day
days
// and a line with an empty string

Upvotes: 1

Related Questions