MENU

Java Find the difference between two dates

TOC

Java Find the difference between two dates

In Java, twoDate DifferenceHere is a sample program to find
The sample program supports the case where the date to be compared is a string ( yyyy/MM/dd ), java.util.

Date DifferenceThe following is the calculation method for determining

  1. The first two dates are converted to long values.
    This long value is the number of milliseconds elapsed since January 1, 1970 00:00:00 GMT.
  2. Next, find the difference.
  3. The difference in dates can be obtained by dividing the quantity from the above calculation by the hours of the day.
    One day (24 hours) is 86,400,000 milliseconds.

sample source


execution (e.g. program)

◆Example of Execution

public static void main(String[] args) {
    int ret = differenceDays("2008/6/2", "2008/6/1");
    System.out.println("result 1 = "+ret);

    ret = differenceDays("2008/6/1", "2008/6/3");
    System.out.println("result 2 = "+ret);

    // May has 31 days
    ret = differenceDays("2008/6/1", "2008/5/1");
    System.out.println("result 3 = "+ret);

    // 30 days in June
    ret = differenceDays("2008/7/1", "2008/6/1");
    System.out.println("result 4 = "+ret);

    // 2008 is a leap year, so the end date of February is the 29th day of the month
    ret = differenceDays("2008/3/1", "2008/2/2/28");
    System.out.println("result 5 = "+ret);");
}

◆Execution Result

Result 1 = 1
Result 2 = -2
Result 3 = 31
Result 4 = 30
Result 5 = 2

Finding the difference between two dates is relatively easy, but finding the difference in months is a bit more challenging. Please see below for reference.
."Java Find the difference between the number of months between two dates"

This sample program is a Chat&Messenger "Calendar and scheduling functionsThe actual use of the system is done in the "I'm a fan of this system.

TOC