Convert a string like "10s" or "10h" to Duration

Viewed 732

I try to parse strings like mentioned in the title to Duration or something similar. Things like Duration.parse() don't work the way I want it to work.

Strings like "10s" or "10h" are given. I need a solution to use that string and convert it to something like Duration or something similar.

Edit: To clarify my needs: I don't want to use "Duration-like" strings with "PTxxx" nor I want to parse those strings on my own. Somewhere out there should be a already implemented solution for that imho.

Any ideas?

3 Answers

Have you checked the documentation? Here is how you can use Duration.parse().

Examples:

"PT20.345S" -- parses as "20.345 seconds"
"PT15M"     -- parses as "15 minutes" (where a minute is 60 seconds)
"PT10H"     -- parses as "10 hours" (where an hour is 3600 seconds)
"P2D"       -- parses as "2 days" (where a day is 24 hours or 86400 seconds)
"P2DT3H4M"  -- parses as "2 days, 3 hours and 4 minutes"
"P-6H3M"    -- parses as "-6 hours and +3 minutes"
"-P6H3M"    -- parses as "-6 hours and -3 minutes"
"-P-6H+3M"  -- parses as "+6 hours and -3 minutes"

So if you want a duration of 10 seconds then Duration.parse("PT10S") or Duration.parse("PT10H") for 10 hours.

Related