Categories
date java

calculate number days between two dates using java

In this tutorial, we will learn about calculate number days between two dates using java

There are lot of ways to calculate number of days between two dates in java

Using Java 8

In below example, we are going to use ChronoUnit to calculate days between two days

Syntax
ChronoUnit.DAYS.between(startDate, endDate);
Example

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class CalculateDaysBetweenDatesJava8 {

	public static void main(String[] args) {
		try {
			// Start date is 2020-03-01 (YYYY-MM-dd)
			LocalDate startDate = LocalDate.of(2020, Month.MARCH, 1);

			// end date is 2020-03--03 (YYYY-MM-dd)
			LocalDate endDate = LocalDate.of(2020, Month.MARCH, 3);

			long numberOfDays = ChronoUnit.DAYS.between(startDate, endDate);

			System.out.println("Number of days " + numberOfDays);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
Number of days 2

Above example is easiest way to calculate days between two dates

Int the below example we are going to use traditional way to calculate days between two days

Below Java 8

In below example we are going to use GregorianCalendar to calculate number of days between two dates

Example

import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalculateDaysUsingCalender {

	public static void main(String[] args) {
		try {
			Calendar startDate = new GregorianCalendar();
			Calendar endDate = new GregorianCalendar();

			// Start date is 2020-03-01 (YYYY-MM-dd)
			startDate.set(2020, 03, 1);

			// end date is 2020-03--03 (YYYY-MM-dd)
			endDate.set(2020, 03, 3);

			// subtract emdTime-StartTime and divide by (1000 * 60 * 60 * 24)
			int i = (int) ((endDate.getTime().getTime() - startDate.getTime().getTime()) / (1000 * 60 * 60 * 24));
			System.out.println("Number of days " + i);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
Number of days 2
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/CalculateDaysUsingCalender.java

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/CalculateDaysBetweenDatesJava8.java

Related Articles

convert String to date in java with example

compare two dates in java example

Leave a Reply

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