java

How to calculate a number of days between two dates in Java

Especially in English-speaking countries, the use of the calendar is very common. The calculation and conversion are done with the class LocalDate in Java 8 and with Calendar in Java before version 8.

In this tutorial, we are going to see two methods to calculate the number of days between two dates in java by using getTime() method and the class LocalDate in Java 8.
 

First method :

Let’s see how to calculate a number of days between two dates by using the getTime() function:

// Get the number of days between two dates
public static long getDaysBetween(Date date1, Date date2) 
{
    long daysBetween = (date1.getTime() - date2.getTime() + 1000000) / 86400000; // 86400000 = 3600 * 24 * 1000 Use immediate numbers to reduce the cost of multiplication calculation 
    return daysBetween;
}
 

Second method :

Let’s see how to calculate a number of days between two dates by using the class LocalDate in Java 8:

import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
 
public class DayBetween {
 
    public static void main(String[] args) {
 
        // Create the LocalDate
        LocalDate date1 = LocalDate.of(2020, 1, 1); // January 1, 2020
        LocalDate date2 = LocalDate.of(2021, 1, 1); // January 1, 2021
 
        // Calculate the number of days
        long dayBetween = DAYS.between(date1, date2);
 
        System.out.println("Number of days: " + dayBetween); //366 days
 
    }
 
}

Output:

Number of days: 366
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *