Here you can find the source of formatMillisecondsToConventional(long duration, int unitCount)
Parameter | Description |
---|---|
duration | a parameter |
unitCount | how many significant units to show, at most for example, a value of 2 would show days+hours or hours+seconds but not hours+second+milliseconds |
time
public static String formatMillisecondsToConventional(long duration, int unitCount)
//package com.java2s; //License from project: Apache License public class Main { /** milliseconds in an hour */ private static final int HOUR_IN_MS = 60 * 60 * 1000; /** milliseconds in a day */ private static final int DAY_IN_MS = 24 * HOUR_IN_MS; /**/*w ww . j av a 2s . c om*/ * Convert milliseconds value to a human-readable duration * @param time * @return Human readable string version of passed <code>time</code> */ public static String formatMillisecondsToConventional(long time) { return formatMillisecondsToConventional(time, 5); } /** * Convert milliseconds value to a human-readable duration of * mixed units, using units no larger than days. For example, * "5d12h13m12s113ms" or "19h51m". * * @param duration * @param unitCount how many significant units to show, at most * for example, a value of 2 would show days+hours or hours+seconds * but not hours+second+milliseconds * @return Human readable string version of passed <code>time</code> */ public static String formatMillisecondsToConventional(long duration, int unitCount) { if (unitCount <= 0) { unitCount = 5; } if (duration == 0) { return "0ms"; } StringBuffer sb = new StringBuffer(); if (duration < 0) { sb.append("-"); } long absTime = Math.abs(duration); long[] thresholds = { DAY_IN_MS, HOUR_IN_MS, 60000, 1000, 1 }; String[] units = { "d", "h", "m", "s", "ms" }; for (int i = 0; i < thresholds.length; i++) { if (absTime >= thresholds[i]) { sb.append(absTime / thresholds[i] + units[i]); absTime = absTime % thresholds[i]; unitCount--; } if (unitCount == 0) { break; } } return sb.toString(); } }