Calculate Days Between Two Dates in Java

Learn how to calculate the number of days between two dates in Java. This code example demonstrates a method to calculate the days between two given dates using the Java programming language. By providing the start and end dates, the program determines the exact number of days between them. This functionality can be useful in various applications such as calculating the duration between events, managing project timelines, or performing date-based calculations.

Example 1:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class CalculateDays {

    public static void main(String[] args) {
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd MM yyyy");
        String fromDate = "12 01 2021";
        String toDate = "28 01 2021";

        LocalDate fromLocalDate = LocalDate.parse(fromDate, dateFormatter);
        LocalDate toLocalDate = LocalDate.parse(toDate, dateFormatter);
        long days = ChronoUnit.DAYS.between(fromLocalDate, toLocalDate) + 1;

        System.out.println("Days " + days);
    }

}

Output:

Days 17


Example 2:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

public class CalculateDays {

    public static void main(String[] args) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy");
        String fromDate = "12 01 2021";
        String toDate = "28 01 2021";

        dateFormat.setTimeZone(TimeZone.getTimeZone("America/"));
        long days = 0;
        try {
            Date dateFrom = dateFormat.parse(fromDate);
            Date dateTo = dateFormat.parse(toDate);
            days = dateTo.getTime() - dateFrom.getTime();
            days = TimeUnit.DAYS.convert(days, TimeUnit.MILLISECONDS) + 1;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        System.out.println("Days " + days);
    }

}

Output:

Days 17