How to Measure Elapsed Time in Java


1.  Introduction

In this example,we will see how to calculate the elapsed time in days, hours, minutes and seconds format.

Source Code

package com.beginner.examples;

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

public class GetsTheTimeDifference {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date startDate = sdf.parse("1999-03-19 00:00:00");
        Date endDate = sdf.parse("2019-04-09 17:15:07");
        long difference = endDate.getTime() - startDate.getTime();
        long diffDays = difference / 1000 / 60 / 60 / 24;
        long diffHours = difference / 1000 / 60 / 60;
        long diffMinutes = difference / 1000 / 60;
        long diffSeconds = difference / 1000;
        System.out.println("startDate: " + startDate + "nendDate: " + endDate + "nDifference: " + diffDays + " days " +
            diffHours % 24 + " hours " + diffMinutes % 60 + " minutes " + diffSeconds % 60 + " seconds");

    }
}

Output:

startDate: Fri Mar 19 00:00:00 CST 1999
endDate: Tue Apr 09 17:15:07 CST 2019
Difference: 7326 days 17 hours 15 minutes 7 seconds

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments