Skip to content

Instantly share code, notes, and snippets.

@svenporto
Created November 29, 2012 20:01
Show Gist options
  • Save svenporto/4171493 to your computer and use it in GitHub Desktop.
Save svenporto/4171493 to your computer and use it in GitHub Desktop.
Milliseconds to days, hours, minutes and seconds
/**
* Formats milliseconds to human readable format "3d 12h 30m 10s"
* in HTML formatting
*
* @param timeInMilliseconds
* @return
*/
public static Spanned getTimeFormatted(long timeInMilliseconds) {
int seconds = (int) (timeInMilliseconds % 60);
timeInMilliseconds /= 60;
int minutes = (int) (timeInMilliseconds % 60);
timeInMilliseconds /= 60;
int hours = (int) (timeInMilliseconds % 24);
timeInMilliseconds /= 24;
int days = (int) timeInMilliseconds;
String result = "";
if(days > 0) {
result += String.format("<b>%s</b>d ", addLeadingZero(days));
}
result += String.format("<b>%s</b>h <b>%s</b>m <b>%s</b>s", addLeadingZero(hours), addLeadingZero(minutes), addLeadingZero(seconds));
return Html.fromHtml(result);
}
public static String addLeadingZero(int amount) {
return new DecimalFormat("#00").format(amount);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment