I want to parse Duration strings in Java 7, like PT45M. I try with SimpleDataFormat but not exist any pattern like PnDTnHnMn.nS. Is there any way to do it?
Asked
Active
Viewed 366 times
2 Answers
3
ThreeTen Backport
As you may or may not be aware, and as the other answer says, the Duration
class of java,time introduced in Java 8 can do that. The good news is that java.time has been backported to Java 6 and 7 too. Get the backport from the link at the bottom and go ahead. For example:
System.out.println("Java version: " + System.getProperty("java.version"));
Duration dur = Duration.parse("PT45M");
System.out.println("Parsed duration: " + dur);
System.out.println("Converted to whole seconds: " + dur.getSeconds());
On my computer output from this piece of code was:
Java version: 1.7.0_67 Parsed duration: PT45M Converted to whole seconds: 2700
Links
- Oracle tutorial: Date Time explaining how to use java.time.
- Java Specification Request (JSR) 310, where
java.time
was first described. - ThreeTen Backport project, the backport of
java.time
to Java 6 and 7 (ThreeTen for JSR-310). - ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
- Wikipedia article: ISO 8601

Ole V.V.
- 81,772
- 15
- 137
- 161
0
Have a look at Java Documentation for Duration. You can convert that string to a duration object via parse method and get seconds with getSeconds() method. Then you can convert seconds to regular java DateTime API objects.

Tuncer T.
- 23
- 1
- 4
-
Hi Tuncer, thanks for the reply, but i have to do this with java 7 otherwise there were no problems. – Cleto Mar 03 '20 at 20:37