public static String formatDuration(long duration, int scale, boolean minDigits) { long hours; long mins; int digits; double millis; hours = duration / 3600000; duration -= hours * 3600000; mins = duration / 60000; duration -= mins * 60000; millis = (double) duration / 1000; StringBuilder buf = new StringBuilder(); if ((hours > 0) || (minDigits == false)) { buf.append(((hours < 10) && (minDigits == false)) ? ("0" + hours) : String.valueOf(hours)).append(':'); minDigits = false; } if ((mins > 0) || (minDigits == false)) { buf.append(((mins < 10) && (minDigits == false)) ? ("0" + mins) : String.valueOf(mins)).append(':'); minDigits = false; } // Format seconds and milliseconds NumberFormat fmt = NumberFormat.getInstance(); digits = (((minDigits == false) || ((scale == 0) && (millis >= 9.5))) ? 2 : 1); fmt.setMinimumIntegerDigits(digits); fmt.setMaximumIntegerDigits(2); // Max of 2 fmt.setMinimumFractionDigits(0); // Don't need any fmt.setMaximumFractionDigits(scale); buf.append(fmt.format(millis)); return buf.toString(); }
private FormattedNumber format(BigDecimal baseTime, int granularity, int milliDigits, Locale locale) { TimeBreakDown tbd; String res; // We work in a few different time ranges depending on the // magnitude of the duration. Quite hardcoded if (granularity == GRANULAR_YEARS) { tbd = this.breakDownTime(baseTime); res = tbd.nYears + "y " + tbd.nDays + "d"; } else if (granularity == GRANULAR_DAYS) { long nDays; tbd = this.breakDownTime(baseTime); nDays = (tbd.nYears * 365) + tbd.nDays; res = nDays + ((nDays == 1) ? " day " : " days ") + StringUtil.formatDuration((tbd.nHours * 60 * 60 * 1000) + (tbd.nMins * 60 * 1000) + (tbd.nSecs * 1000) + tbd.nMilli); } else if ((granularity == GRANULAR_HOURS) || (granularity == GRANULAR_MINS) || (granularity == GRANULAR_SECS)) { long nMillis; nMillis = baseTime.divide(UnitsUtil.FACT_MILLIS, BigDecimal.ROUND_HALF_EVEN).longValue(); res = StringUtil.formatDuration(nMillis, milliDigits, granularity == GRANULAR_SECS); if (granularity == GRANULAR_SECS) { res = res + 's'; } } else { throw new IllegalStateException("Unexpected granularity"); } return new FormattedNumber(res.trim(), ""); }