javastringdurationreformat

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.


Solution

  • 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.