Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most idiomatic way to print a time difference in Java?

I'm familiar with printing time difference in milliseconds:

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

But, is there a nice way print a complete time in a specified format (eg: HH:MM:SS) either using Apache Commons or even the dreaded platform API's Date/Time objects? In other words, what is the shortest, simplest, no nonsense way to write a time format derived from milliseconds in Java?

like image 804
Zombies Avatar asked Apr 24 '10 12:04

Zombies


People also ask

How to print time difference in Java?

Parse both start_date and end_date from a string to produce the date, this can be done by using parse() method of the simpleDateFormat class. Find the time difference between two dates in millisecondes by using the method getTime() in Java as d2. getTime() – d1. getTime().

How do you subtract time in Java?

String start = "12:00:00"; String end = "02:05:00"; SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); Date date1 = format. parse(start); Date date2 = format. parse(end); long difference = date2. getTime() - date1.


2 Answers

Apache Commons has the DurationFormatUtils class for applying a specified format to a time duration. So, something like:

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

DurationFormatUtils.formatDuration(completedIn, "HH:mm:ss:SS");
like image 88
Bill the Lizard Avatar answered Oct 05 '22 23:10

Bill the Lizard


A library designed for the purpose is the better approach, but SimpleDateFormat with the right TimeZone may suffice for periods less than a day. Longer periods require treating the day specially.

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));
        }
    }
}

Console output:

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
like image 28
trashgod Avatar answered Oct 05 '22 23:10

trashgod