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.
publicstaticvoid main(String args)
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
// Set the date for both of the calendar instance
c1.set(2020, 0, 1);
c2.set(2020, 2, 1);
// Print out the dates
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");