Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert javax.xml.datatype.Duration

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.

like image 844
Yadvendra Avatar asked Jan 08 '23 04:01

Yadvendra


2 Answers

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.

like image 199
Meno Hochschild Avatar answered Feb 02 '23 21:02

Meno Hochschild


    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.

like image 36
Anand Avatar answered Feb 02 '23 21:02

Anand