UPDATE

The original answer from 2013 is now outdated because some of the classes have been replaced. The new way of doing this is using the new java.time classes.

24-hour days

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    LocalDateTime date1 = LocalDate.parse(inputString1, dtf).atStartOfDay();
    LocalDateTime date2 = LocalDate.parse(inputString2, dtf).atStartOfDay();
    long daysBetween = Duration.between(date1, date2).toDays();
    System.out.println ("Days: " + daysBetween);
} catch (DateTimeParseException e) {
    e.printStackTrace();
}

Calendar days

Note that the solution above counts days as generic chunks of 24 hours, not calendar days.

For calendar days, use java.time.temporal.ChronoUnit.DAYS and its between method.

long daysBetween = ChronoUnit.DAYS.between(date1, date2) ;

Original answer (outdated as of Java 8)

You are making some conversions with your Strings that are not necessary. There is a SimpleDateFormat class for it - try this:

SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    Date date1 = myFormat.parse(inputString1);
    Date date2 = myFormat.parse(inputString2);
    long diff = date2.getTime() - date1.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}

There have been some discussions regarding the correctness of this code. It does indeed take care of leap years. However, the TimeUnit.DAYS.convert function loses precision since milliseconds are converted to days (see the linked doc for more info). If this is a problem, diff can also be converted by hand:

float days = (diff / (1000*60*60*24));

Note that this is a float value, not necessarily an int.

Answer from influjensbahr on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_date.asp
Java Date and Time
Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Date.html
Date (Java Platform SE 8 )
1 week ago - Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases.
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › util › Date.html
Date (Java Platform SE 7 )
Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases.
🌐
Baeldung
baeldung.com › home › java › java dates › extract year, month and day from date in java
Extracting Year, Month and Day from Date in Java | Baeldung
July 14, 2024 - Finally, to extract the day, we invoke get by passing Calendar.DAY_OF_MONTH as an argument: ... For a given java.sql.Timestamp, to extract individual fields such as Year, Month, Day, etc., the first step we need to do is convert it to a Calendar instance:
🌐
Mkyong
mkyong.com › home › java › java – how to add days to current date
Java - How to add days to current date - Mkyong.com
November 15, 2016 - ... package com.mkyong.time; import ... DateExample { private static final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); public static void main(String[] args) { Date currentDate = new Date(); ...
Top answer
1 of 16
319

UPDATE

The original answer from 2013 is now outdated because some of the classes have been replaced. The new way of doing this is using the new java.time classes.

24-hour days

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    LocalDateTime date1 = LocalDate.parse(inputString1, dtf).atStartOfDay();
    LocalDateTime date2 = LocalDate.parse(inputString2, dtf).atStartOfDay();
    long daysBetween = Duration.between(date1, date2).toDays();
    System.out.println ("Days: " + daysBetween);
} catch (DateTimeParseException e) {
    e.printStackTrace();
}

Calendar days

Note that the solution above counts days as generic chunks of 24 hours, not calendar days.

For calendar days, use java.time.temporal.ChronoUnit.DAYS and its between method.

long daysBetween = ChronoUnit.DAYS.between(date1, date2) ;

Original answer (outdated as of Java 8)

You are making some conversions with your Strings that are not necessary. There is a SimpleDateFormat class for it - try this:

SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    Date date1 = myFormat.parse(inputString1);
    Date date2 = myFormat.parse(inputString2);
    long diff = date2.getTime() - date1.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}

There have been some discussions regarding the correctness of this code. It does indeed take care of leap years. However, the TimeUnit.DAYS.convert function loses precision since milliseconds are converted to days (see the linked doc for more info). If this is a problem, diff can also be converted by hand:

float days = (diff / (1000*60*60*24));

Note that this is a float value, not necessarily an int.

2 of 16
149

Simplest way:

public static long getDifferenceDays(Date d1, Date d2) {
    long diff = d2.getTime() - d1.getTime();
    return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}
🌐
How to do in Java
howtodoinjava.com › home › java date time › add or subtract days, months & years to date in java
Add or Subtract Days, Months & Years to Date in Java
February 23, 2022 - Java examples to add or subtract days, months or years from java 7 Date and Java 8 LocalDate, LocalDateTime classes.
🌐
How to do in Java
howtodoinjava.com › home › java date time › number of days between two dates in java
Number of Days between Two Dates in Java
October 15, 2024 - In Java, we can use the ChronoUnit and LocalDate.until() methods to calculate the number of days between two given dates. Other solutions exist, but these are the simplest and do not require importing an additional library.
Find elsewhere
🌐
BeginnersBook
beginnersbook.com › 2017 › 10 › java-add-days-to-date
Java – Add days to Date
September 11, 2022 - Java Date format 4. Java Date Parsing 5. Java 8 – Calculate Days between two given dates
🌐
Attacomsian
attacomsian.com › blog › java-add-days-to-date
How to add days to a date in Java
October 14, 2022 - A quick tutorial to learn how to add days to a date using Java 8 new date and time API as well as the legacy Date and Calendar API.
🌐
Stack Abuse
stackabuse.com › how-to-get-the-number-of-days-between-dates-in-java
How to Get the Number of Days Between Dates in Java
May 4, 2022 - All of the if-clauses and checks could get pretty verbose quickly, so it's highly advised to stick to the between() method for getting the number of days between dates. The standard date and time classes before Java 8 were known to be poor, and so Joda-Time became the standard date and time library that was most widely used at the time.
🌐
BeginnersBook
beginnersbook.com › 2017 › 10 › java-8-calculate-days-between-two-dates
Java 8 – Calculate days between two dates
September 11, 2022 - long noOfDaysBetween = DAYS.between(startDate, endDate); // or alternatively long noOfDaysBetween = startDate.until(endDate, DAYS); The startDate is Inclusive and endDate is Exclusive in the calculation of noOfDaysBetween · Lets see the complete example of how to use this method. import java.time.LocalDate; import java.time.Month; import java.time.temporal.ChronoUnit; public class Example { public static void main(String[] args) { //24-May-2017, change this to your desired Start Date LocalDate dateBefore = LocalDate.of(2017, Month.MAY, 24); //29-July-2017, change this to your desired End Date LocalDate dateAfter = LocalDate.of(2017, Month.JULY, 29); long noOfDaysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter); System.out.println(noOfDaysBetween); } }
🌐
Oracle
docs.oracle.com › en › java › javase › 26 › docs › api › java.base › java › util › Date.html
Date (Java SE 26 & JDK 26)
1 week ago - Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases.
🌐
Baeldung
baeldung.com › home › java › java dates › increment date in java
Increment Date in Java | Baeldung
January 8, 2024 - An overview of various core and 3rd party methods for adding days to a date