Skip to content

Instantly share code, notes, and snippets.

@gabrielstelmach
Last active December 9, 2017 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabrielstelmach/c3defec76e6314c5a32434cb6c79eb18 to your computer and use it in GitHub Desktop.
Save gabrielstelmach/c3defec76e6314c5a32434cb6c79eb18 to your computer and use it in GitHub Desktop.
Formatting a specific amount of time in a friendly way
/**
* Formats the amount of time in a friendly way.
*
* @param millis Amount of time in milliseconds.
* @param nicly When the amount of time is less than 1 minute, the message will be cool.
* @return Friendly description of the amount of time.
*/
public static String friendlyAmountTime(long millis, boolean nicly)
{
long hours = TimeUnit.MILLISECONDS.toHours(millis);
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
StringBuilder sb = new StringBuilder();
if (nicly)
{
sb.append("Really fast!");
}
else
{
sb.append("< 1 second");
}
if (millis > 999)
{
sb.delete(0, sb.length());
if (hours > 0)
{
sb.append(hours);
sb.append(" hour");
if (hours > 1)
{
sb.append("s");
}
}
if (minutes > 0)
{
sb.append(" ");
sb.append(minutes);
sb.append(" minute");
if (minutes > 1)
{
sb.append("s");
}
}
if (seconds > 0)
{
sb.append(" ");
sb.append(seconds);
sb.append(" second");
if (seconds > 1)
{
sb.append("s");
}
}
}
return sb.toString().trim();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment