Skip to content
Advertisement

Why is this input an invalid format for Joda-Time PeriodFormatter?

I am trying to convert strings like 1h 30m 5s or 5m or 38s or 1h 3s into an integer value representing total time in seconds. So for example, 1m 20s would result in an integer value of 80 for 80 seconds.

I am using Joda Time:

PeriodFormatter formatter = new PeriodFormatterBuilder()
        .appendDays().appendSuffix("d").appendSeparatorIfFieldsAfter(" ")
        .appendHours().appendSuffix("h").appendSeparatorIfFieldsAfter(" ")
        .appendMinutes().appendSuffix("m").appendSeparatorIfFieldsAfter(" ")
        .appendSeconds().appendSuffix("s")
        .toFormatter();

int time = formatter.parsePeriod("30s").getSeconds(); //Throws IllegalArgumentException

Throws an IllegalArgumentException with practically every string i pass in, saying “Invalid format”.

I don’t understand why this wouldn’t be working. I can’t pass ANYTHING into this without getting an illegalArgumentException. Does anybody have any guidance on how to tweak my formatter settings to achieve my desired result?

Advertisement

Answer

The Joda-Time project is now in maintenance mode. It’s creator went on to lead JSR 310 which brought the java.time classes now built into Java 8 and later.

The ISO 8601 standard format for a span of time unattached to the timeline is PnYnMnDTnHnMnS where the P marks the beginning, and the T separates the two portions.

The java.time classes use the ISO 8601 standard formats by default when parsing/generating text. So no need to specify a formatting pattern.

So I would solve your problem with simple text manipulation. Delete your SPACE characters. Change to uppercase.

java.time.Duration.parse( "PT" + "1h 30m 5s".replace( " " , "" ).toUpperCase() )
Advertisement