Search code examples
javaandroidkotlinsimpledateformatdate-format

How to parse duration format from duration in JAVA?


I have a duration format which is like 0DT3H10M. So need to know how to parse this kind of data.

I want 0 Days 3 Hours and 10 Minutes from 0DT3H10M

in a specific format.

We can manually parse it by a character which is working fine but is there any other way or library available for this in android/java?


Solution

  • Duration

    I will guess that string represents a duration of three hours and ten minutes.

    Unfortunately that string fails to comply with the ISO 8601 standard used by default in the java.time classes Duration and Period. The standard starts all such strings with a P. And the standard separates any years-months-days from any hours-minutes-seconds with a T. So your input of three hours and ten minutes would be PT3H10M.

    You will need to parse the string with your own code. Then use the extracted values to set the value of a java.time.Duration object.

    You may be able to get away with simply prepending a P to comply with the standard. I hesitate to recommend this only because you would need to see the range of possible values you might receive to verify this approach would work.

    Duration.parse( "P" + "0DT3H10M" )
    

    Tip: Educate the publisher of your input data about ISO 8601.