Compute the difference between Two dates in Java

0 comments
This example shows how to compute the difference between two dates. It shows how to compute the difference between the dates in days, hours, minutes, seconds and even milliseconds.


We use the Calendar class to create two instances and set the respective dates on each of them.

In the example we set the date January 1, 2020 as the first date and March 1, 2020 as the second date.

Just to make sure we got it right (remember that the month field in Calendar and Date object are zero based, meaning that January = 0) we print them out using a SimpleDateFormat instance to make them readable.

To compute the difference in milliseconds we call the method getTimeInMillis() on the Calendar class. The millisecond-difference is then used to compute every other unit in the example.


Immediately after each calculation the result is printed out to console.



package com.javadb.examples;


import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Main
{
    public static void main(String[] args)
    {
        Calendar c1 = Calendar.getInstance();
        c1.clear();

        Calendar c2 = Calendar.getInstance();
        c2.clear();

        // Set the date for both of the calendar instance
        c1.set(202001);
        c2.set(202021);

        // Print out the dates
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("Date 1: " + sdf.format(c1.getTime()));
        System.out.println("Date 2: " + sdf.format(c2.getTime()));

        // Get the represented date in milliseconds
        long time1 = c1.getTimeInMillis();
        long time2 = c2.getTimeInMillis();

        // Calculate difference in milliseconds
        long diff = time2 - time1;

        // Difference in seconds
        long diffSec = diff 1000;
        System.out.println("Difference in seconds " + diffSec);

        // Difference in minutes
        long diffMin = diff (60 * 1000);
        System.out.println("Difference in minutes " + diffMin);

        // Difference in hours
        long diffHours = diff (60 * 60 * 1000);
        System.out.println("Difference in hours " + diffHours);

        // Difference in days
        long diffDays = diff (24 * 60 * 60 * 1000);
        System.out.println("Difference in days " + diffDays);
    }
}



READ MORE >>

0 comments: