4

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.

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
Droy
  • 173
  • 2
  • 17

2 Answers2

9

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
  • Thank you very much.... this worked like charm... I'm new to stackoverflow so cannot upvote you(below 15 reputation points) but this was awesome and deserves more than 1000 upvotes. Thank You – Droy Jun 12 '15 at 13:19
  • @Yadvendra Happy to have helped you. If you want to honor this answer anyway you can simply accept it. – Meno Hochschild Jun 12 '15 at 13:34
  • Thanks.. I actually didn't knew how to accept either..;p one more thing... is there a way to convert the total to hours. Like if duration = P2DT10H45M0S converted string = 58 Hrs 45 Min I think there's one solution i think may work. Duration dur = DatatypeFactory.newDuration("P2DT15H45M0S"); int days = dur.getDays(); int hours = dur.getHours(); int minutes = dur.getMinutes(); for(int i=0;i – Droy Jun 12 '15 at 14:21
  • @Yadvendra If you only want hours then make sure that your duration does not contain months or years. Otherwise you can iterate over all units and use `java.util.concurrent.TimeUnit` for conversion to hours (one day would here always be like 24 hours - ignoring rare cases like dst change) and finally sum up all hour parts.. – Meno Hochschild Jun 12 '15 at 19:09
  • Thanks.. I did the way mentioned in the previous comment and it worked as expected.(Yes my duration does not contain years or months). – Droy Jun 13 '15 at 08:16
1
    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.

Anand
  • 1,845
  • 2
  • 20
  • 25