假设以下是毫秒的声明:
long millis = 5000000;
现在从毫秒获取小时,分钟和秒:
long hours = TimeUnit.MILLISECONDS.toHours(millis); long minutes = TimeUnit.MILLISECONDS.toMinutes(millis) - (hours * 60); long seconds = TimeUnit.MILLISECONDS.toSeconds(millis) - ((hours * 60 * 60) + (minutes * 60));
使用String.format()将上面的内容转换为可读的字符串。
import java.util.concurrent.TimeUnit; public class Demo { public static void main(String[] argv){ long millis = 5000000; long hours = TimeUnit.MILLISECONDS.toHours(millis); long minutes = TimeUnit.MILLISECONDS.toMinutes(millis) - (hours * 60); long seconds = TimeUnit.MILLISECONDS.toSeconds(millis) - ((hours * 60 * 60) + (minutes * 60)); millis = millis - ((hours * 60 * 60 * 1000) + (minutes * 60 * 1000) + (seconds * 1000)); System.out.println(String.format("Hours = %d\nMinutes = %d\nSeconds = %d\nMilliseconds = %d", hours, minutes, seconds, millis)); System.out.println(String.format("%d hr(s) %d min(s) %d sec(s) %d ms", hours, minutes, seconds, millis)); } }
输出结果
Hours = 1 Minutes = 23 Seconds = 20 Milliseconds = 0 1 hr(s) 23 min(s) 20 sec(s) 0 ms