最常用的方法是在Java中打印时差吗?

Zom*_*ies 16 java datetime idioms code-formatting

我熟悉以毫秒为单位的打印时差:

 long time = System.currentTimeMillis();
 //do something that takes some time...
 long completedIn = System.currentTimeMillis() - time;
Run Code Online (Sandbox Code Playgroud)

但是,使用Apache Commons甚至是可怕的平台API的日期/时间对象,是否有一种很好的方式以指定的格式打印完整的时间(例如:HH:MM:SS)?换句话说,在Java中编写从毫秒派生的时间格式的最短,最简单,没有废话的方法是什么?

Bil*_*ard 22

Apache Commons具有DurationFormatUtils类,用于将指定格式应用于持续时间.所以,像:

long time = System.currentTimeMillis();
//do something that takes some time...
long completedIn = System.currentTimeMillis() - time;

DurationFormatUtils.formatDuration(completedIn, "HH:mm:ss:SS");
Run Code Online (Sandbox Code Playgroud)

  • 或者使用几乎完全相同的内置DurationFormatUtils.formatDurationHMS(end-start); (5认同)
  • 是的!虽然`formatDurationHMS`不太符合要求,因为它是'H:m:s`而不是'HH:mm:ss`,但我只是想指出它是一种可能性. (2认同)

tra*_*god 5

为此目的而设计的图书馆是更好的方法,但SimpleDateFormat权利TimeZone可能足以满足不到一天的时间.更长的时间需要特别处理一天.

import java.text.DateFormat;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

public class Elapsed {

    private static final long MS_DAY = 24 * 60 * 60 * 1000;
    private final DateFormat df = new SimpleDateFormat("HH : mm : ss : S");

    public Elapsed() {
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
    }

    private String format(long elapsed) {
        long day = elapsed / MS_DAY;
        StringBuilder sb = new StringBuilder();
        sb.append(day);
        sb.append(" : ");
        sb.append(df.format(new Date(elapsed)));
        return sb.toString();
    }

    public static void main(String[] args) {
        Elapsed e = new Elapsed();
        for (long t = 0; t < 3 * MS_DAY; t += MS_DAY / 2) {
            System.out.println(e.format(t));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

控制台输出:

0 : 00 : 00 : 00 : 0
0 : 12 : 00 : 00 : 0
1 : 00 : 00 : 00 : 0
1 : 12 : 00 : 00 : 0
2 : 00 : 00 : 00 : 0
2 : 12 : 00 : 00 : 0