Java 程序将毫秒转换成可读字符串


我们假设毫秒的声明如下

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
Minutes = %d
Seconds = %d
Milliseconds =          %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

更新于: 30-7-2019

563 浏览

开启你的职业生涯

完成课程获取认证

开始
广告