$show=/label

Calculate Days Between Two Dates In Java 8 and Older JDK

SHARE:

A quick guide how to find the number of days between two given dates in java 8 and older versions of 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?

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,23,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,84,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,12,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,10,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,77,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,93,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,23,String,58,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Calculate Days Between Two Dates In Java 8 and Older JDK
Calculate Days Between Two Dates In Java 8 and Older JDK
A quick guide how to find the number of days between two given dates in java 8 and older versions of JDK.
https://1.bp.blogspot.com/-PhdlMgDfBi0/X7V3qiKsHAI/AAAAAAAADEY/YCXur0M2keoYdqa8gg6svqh1Sz6ufKFtQCLcBGAsYHQ/w640-h400/Calculate%2BDays%2BBetween%2BTwo%2BDates%2BIn%2BJava%2B8%2Band%2BOlder%2BJDK.png
https://1.bp.blogspot.com/-PhdlMgDfBi0/X7V3qiKsHAI/AAAAAAAADEY/YCXur0M2keoYdqa8gg6svqh1Sz6ufKFtQCLcBGAsYHQ/s72-w640-c-h400/Calculate%2BDays%2BBetween%2BTwo%2BDates%2BIn%2BJava%2B8%2Band%2BOlder%2BJDK.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/11/calculate-days-between-two-dates-in.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/11/calculate-days-between-two-dates-in.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content