public String formatDuration ( Object obj ) { javax . xml . datatype . DatatypeConstants . Field inFields [ ] = { javax . xml . datatype . DatatypeConstants . YEARS , javax . xml . datatype . DatatypeConstants . MONTHS , javax . xml . datatype . DatatypeConstants . DAYS , javax . xml . datatype . DatatypeConstants . HOURS , javax . xml . datatype . DatatypeConstants . MINUTES , javax . xml . datatype . DatatypeConstants . SECONDS , } ; TimeUnit outFields [ ] = { TimeUnit . YEAR , TimeUnit . MONTH , TimeUnit . DAY , TimeUnit . HOUR , TimeUnit . MINUTE , TimeUnit . SECOND , } ; javax . xml . datatype . Duration inDuration = ( javax . xml . datatype . Duration ) obj ; Period p = null ; javax . xml . datatype . Duration duration = inDuration ; boolean inPast = false ; if ( inDuration . getSign ( ) < 0 ) { duration = inDuration . negate ( ) ; inPast = true ; } // convert a Duration to a Period boolean sawNonZero = false ; // did we have a set, non-zero field? for ( int i = 0 ; i < inFields . length ; i ++ ) { if ( duration . isSet ( inFields [ i ] ) ) { Number n = duration . getField ( inFields [ i ] ) ; if ( n . intValue ( ) == 0 && ! sawNonZero ) { continue ; // ignore zero fields larger than the largest nonzero field } else { sawNonZero = true ; } float floatVal = n . floatValue ( ) ; // is there a 'secondary' unit to set? TimeUnit alternateUnit = null ; float alternateVal = 0 ; // see if there is a fractional part if ( outFields [ i ] == TimeUnit . SECOND ) { double fullSeconds = floatVal ; double intSeconds = Math . floor ( floatVal ) ; double millis = ( fullSeconds - intSeconds ) * 1000.0 ; if ( millis > 0.0 ) { alternateUnit = TimeUnit . MILLISECOND ; alternateVal = ( float ) millis ; floatVal = ( float ) intSeconds ; } } if ( p == null ) { p = Period . at ( floatVal , outFields [ i ] ) ; } else { p = p . and ( floatVal , outFields [ i ] ) ; } if ( alternateUnit != null ) { p = p . and ( alternateVal , alternateUnit ) ; // add in MILLISECONDs } } } if ( p == null ) { // no fields set = 0 seconds return formatDurationFromNow ( 0 ) ; } else { if ( inPast ) { // was negated, above. p = p . inPast ( ) ; } else { p = p . inFuture ( ) ; } } // now, format it. return pformatter . format ( p ) ; }
JDK 1 . 5 + only