how to convert javax.xml.datatype.Duration

9.5k views Asked by At

I have a response from server in javax.xml.datatype.Duration format.
This is what I get
Travel Duration = P2DT15H45M0S
and I want it in format
required format = 2 Days 15 Hrs 45 Min
How to do this?
Is there any way to convert from javax.xml.datatype.Duration to String.

Thank you.

2

There are 2 answers

5
Meno Hochschild On BEST ANSWER

A simple and straight-forward solution without an external library (there is no built-in duration formatter in Java):

Duration dur = DatatypeFactory.newInstance().newDuration("P2DT15H45M0S");
int days = dur.getDays();
int hours = dur.getHours();
int minutes = dur.getMinutes();

String formatted = days + " Days " + hours + " Hrs " + minutes + " Min"

If you want singular forms like " Day " in case one duration part is just equal to 1 that is up to you to add a small enhancement to this code. Maybe you also need to normalize your duration first (for example if your second part is beyond 59), see javadoc.

0
Anand On
    public static Duration convertXmlTypeDuration(String input) throws DatatypeConfigurationException {
       // Duration duration =
       // DatatypeFactory.newInstance().newDuration("P2DT23H59M0S");
       Duration duration = DatatypeFactory.newInstance().newDuration(input);
       return duration;
}

You can get days, hours and minutes from duration.