Pages

Thursday, November 19, 2020

Calculate Days Between Two Dates In Java 8 and Older JDK

1. Overview

In this tutorial, you'll learn how to calculate the days between two dates in java 8 and previous versions of java.

First, let us show the examples on the old java version and then with the new JDK 8 date time api feature.

Calculate Days Between Two Dates In Java 8 and Older JDK


2. Before Java 8 - Find No of days between two dates

This is very simple. First, create two date objects with the lower days differences so that we can understand the example easily.

After that get the time in milli seconds using date.getTime() method for two dates. Get the difference and convert milli seconds value into days using diff/ (1000 * 60 * 24).

That's all. Logic is simple. 

Let us write a simple example program to work with dates.

import java.util.Date;

/**
 * 
 * @author javaprogramto.com
 *
 */
public class CalculatedNoOfDaysExample {
	
	public static void main(String[] args) {
		
		// creating the date 1 with sample input date.
		Date date1 = new Date(2020, 11, 1);
		
		// creating the date 2 with sample input date.
		Date date2 = new Date(2020, 11, 30);
		
		// getting milliseconds for both dates
		long date1InMs = date1.getTime();
		long date2InMs = date2.getTime();
		
		// getting the diff between two dates.
		long timeDiff = 0;
		if(date1InMs > date2InMs) {
			timeDiff = date1InMs - date2InMs;
		} else {
			timeDiff = date2InMs - date1InMs;
		}
		
		// converting diff into days
		int daysDiff = (int) (timeDiff / (1000 * 60 * 60* 24));
		
		// print diff in days
		System.out.println("No of days diff is : "+daysDiff);
		
	}

}

Output:

No of days diff is : 29

From the above output, you can observe that our logic is working fine and show the diff is 29 correct value.

3. Before Java 8 - Find No of days between two dates in String format

Next example, Let us take two strings that contains dates. First need to convert String to Date and next apply the above same logic. 

That should give the different between two string dates.

If you don't understand the example, please read the inline comments in the program.

public class CalculatedNoOfDaysDatesInStringExample {	
	public static void main(String[] args) throws ParseException {
		// input string date format
		String DATE_FORAT = "yyyy-MM-dd";
		
		// creating simple date formatter using string format
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORAT);
		
		// Create two Dates in String varaible
		String dateStr1 = "2021-01-01";
		String dateStr2 = "2021-01-31";
		
		// converting string dateStr1 to date using simpledateformat.
		Date date1 = simpleDateFormat.parse(dateStr1);
		
		// converting string dateStr2 to date using simpledateformat.
		Date date2 = simpleDateFormat.parse(dateStr2);;
		
		// getting milliseconds for both dates
		long date1InMs = date1.getTime();
		long date2InMs = date2.getTime();
		
		// getting the diff between two dates.
		long timeDiff = 0;
		if(date1InMs > date2InMs) {
			timeDiff = date1InMs - date2InMs;
		} else {
			timeDiff = date2InMs - date1InMs;
		}
		
		// converting diff into days
		int daysDiff = (int) (timeDiff / (1000 * 60 * 60* 24));
		
		// print diff in days
		System.out.println("No of days diff is using String Dates : "+daysDiff);
		
	}
}

Output:

No of days diff is using String Dates : 30

4. New Java 8 - Find No of days between two dates

As of now, you've seen how to find the no of days and what is the difference between two days in older java versions.

But the same can be done with java 8 date time api in simple steps.

Java 8 api provides two simple ways using the following methods.

// Java 8 way 1
long noOfDaysBetween = ChronoUnit.DAYS.between(date1, date2);

// Java 8 way 2
long noOfDaysBetween = date1.until(date2, ChronoUnit.DAYS);

Let us explore these two method and how can be retrieved the difference among two dates.

First, you need to know about the LocalDate class in java 8 which is similarly Date class in old java.

Next, create two LocalDate objects with date1 and date2 values using LocalDate.of() method.

Afterwards, call between() method passing two LocalDate objects and print the returned value to console.

package com.javaprogramto.java8.dates.diff.days;

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

public class Java8CalculatedNoOfDaysExample {

	public static void main(String[] args) {
		// java 8 way - 1

		// creating LocalDate object 1 using LocalDate.of() method.
		LocalDate localDate1 = LocalDate.of(2021, Month.JANUARY, 1);

		// creating the date 2 with sample input date.
		LocalDate localDate2 = LocalDate.of(2021, Month.JANUARY, 31);

		// Fetching the diff using between() method
		long noOfDaysDifference = ChronoUnit.DAYS.between(localDate1, localDate2);

		// print diff in days
		System.out.println("Java 8 way 1 between() - No of days diff is : " + noOfDaysDifference);

		// java 8 way - 2

		// using until() method
		noOfDaysDifference = localDate1.until(localDate2, ChronoUnit.DAYS);

		System.out.println("Java 8 way 2 untill() - No of days diff is : " + noOfDaysDifference);

	}

}

If you use java 8 then no need to get the time in milli seconds and converting to days using manual mathematical formulae. Instead, directly can get the days using between() or until() method.

Output:

Java 8 way 1 between() - No of days diff is : 30
Java 8 way 2 untill() - No of days diff is : 30

5. New Java 8 - Find No of days between two dates in string format

In the above examples, Dates are in needed format but some of the scenarios you might get the dates in the other format such as String type.

In such cases, First you need to convert the string dates into local dates using LocalDate.parse() method. No need to specify the explicitly the date format if it is in the ISO date format as "yyyy-MM-dd".

Look at the below example.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class Java8CalculatedNoOfDaysDatesInStringExample {

	public static void main(String[] args) throws ParseException {

		// Create two Dates in String variable
		String dateStr1 = "2021-05-01";
		String dateStr2 = "2021-05-16";

		// parsing the string date into LocalDate objects.
		LocalDate localDate1 = LocalDate.parse(dateStr1);
		LocalDate localDate2 = LocalDate.parse(dateStr2);

		// java 8 way - 1
		// Fetching the diff using between() method
		long noOfDaysDifference = ChronoUnit.DAYS.between(localDate1, localDate2);

		// print diff in days
		System.out.println("Java 8 way 1 between() - No of days diff is : " + noOfDaysDifference);

		// java 8 way - 2
		// using until() method
		noOfDaysDifference = localDate1.until(localDate2, ChronoUnit.DAYS);

		System.out.println("Java 8 way 2 untill() - No of days diff is : " + noOfDaysDifference);

	}
}

Output:

Java 8 way 1 between() - No of days diff is : 15
Java 8 way 2 untill() - No of days diff is : 15

6. Conclusion

In this article, you've seen how to calculate days between two dates in java 8 with examples programs.

It is simple if you use java 8 methods such as between() or until() methods.

GitHub

CalculatedNoOfDaysExample

CalculatedNoOfDaysDatesInStringExample

Java8CalculatedNoOfDaysExample

Java8CalculatedNoOfDaysDatesInStringExample


ChronoUnit.between()

LocalDate

How to convert String to Date in older JDK?

No comments:

Post a Comment

Please do not add any spam links in the comments section.