将Java中的时长(long型毫秒)等格式,转换为方便查看的时间格式(经过时长多少天、多少小时、多少分钟)。
/**
* 将时间转换为天、小时、分钟
*
* @param duration 时长(毫秒)
* @return 格式化
*/
private static String millisToShortDHMS(long duration) {
String res = "";
long days = TimeUnit.MILLISECONDS.toDays(duration);
long hours = TimeUnit.MILLISECONDS.toHours(duration)
- TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));
long seconds = TimeUnit.MILLISECONDS.toSeconds(duration)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));
if (days == 0) {
if (hours == 0) {
res = String.format("%d分钟", minutes);
} else {
res = String.format("%d小时%d分钟", hours, minutes);
}
} else {
res = String.format("%d天%d小时%d分钟", days, hours, minutes);
}
return res;
}
参考文章:
1. Format a duration in milliseconds into a human-readable format;
2. Java – Time elapsed in days, hours, minutes, seconds;