LoginSignup
5
6

More than 5 years have passed since last update.

経過時間を測定時、mm:ss:SSS表記にする方法

Posted at

どんなとき使うか

普通にやるとミリ秒で結果が表示されて計算が必要になるので、可視性を高めたいときに使う。

やり方1

commons-langライブラリが使えないとき

public static void main(String[] args) {

    long startTime = System.currentTimeMillis();

    //テスト用
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    long endTime = System.currentTimeMillis();

    System.out.println(format(startTime, endTime));


}

private static String format(long startTime, long endTime) {
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    Calendar result = Calendar.getInstance();

    start.setTimeInMillis(startTime);
    end.setTimeInMillis(endTime);

    long sa = end.getTimeInMillis() - start.getTimeInMillis() - result.getTimeZone().getRawOffset();

    result.setTimeInMillis(sa);

    SimpleDateFormat sdf = new SimpleDateFormat("mm:ss:SSS");

    return sdf.format(result.getTime());
}

やり方2

commons-langライブラリが使えるとき
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DurationFormatUtils.html

private static String format(long startTime, long endTime) {

    String diffTime = DurationFormatUtils.formatPeriod(startTime,
            endTime, "HH:mm:ss.SSS");

    return diffTime;

}
5
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6