1

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?

Cleto
  • 49
  • 2

2 Answers2

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

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