Here you can find the source of formatDuration(long millis)
Parameter | Description |
---|---|
millis | - The amount of time in milliseconds |
public static String formatDuration(long millis)
//package com.java2s; //License from project: Open Source License import java.util.concurrent.TimeUnit; public class Main { /**/* w w w . j a v a2 s . c o m*/ * This will return a rounded String representation of the given duration in milliseconds * with a minimum of 1 time unit and a maximum of 2 time units.<br> * Examples: * <ul> * <li>3785300: 1 hr, 3 min</li> * <li>81074000: 22 hrs, 31 min</li> * <li>97440000: 1 day, 3 hrs</li> * <li>478200: 7 minutes</li> * <li>18056000: 5 hours</li> * </ul> * @param millis - The amount of time in milliseconds * @return - the amount of time passed in the format of:<br> * # day(s), # (hour|hr)(s), # (minute|min)(s), # second(s) */ public static String formatDuration(long millis) { String formattedTimer = ""; int days = (int) TimeUnit.MILLISECONDS.toDays(millis); long hours = TimeUnit.MILLISECONDS.toHours(millis) - (days * 24); long minutes = TimeUnit.MILLISECONDS.toMinutes(millis) - (TimeUnit.MILLISECONDS.toHours(millis) * 60); long seconds = TimeUnit.MILLISECONDS.toSeconds(millis) - (TimeUnit.MILLISECONDS.toMinutes(millis) * 60); if (days != 0) { formattedTimer += days + " day" + (days > 1 ? "s" : ""); } if (hours != 0) { String unit = (days > 0 || (days == 0 && minutes > 0) ? " hr" : " hour") + (hours > 1 ? "s" : ""); formattedTimer += (formattedTimer.length() != 0 ? ", " : "") + hours + unit; } if (minutes != 0 && days == 0) { String unit = (hours > 0) ? " min" : " minute" + (minutes > 1 ? "s" : ""); formattedTimer += (formattedTimer.length() != 0 ? ", " : "") + minutes + unit; } if (seconds != 0 && days == 0 && hours == 0 && minutes == 0) { String unit = " second" + (seconds > 1 ? "s" : ""); formattedTimer += (formattedTimer.length() != 0 ? ", " : "") + seconds + unit; } return !formattedTimer.isEmpty() ? formattedTimer : "0 seconds"; } }