$show=/label

How To Compare Two Dates In Java and New Java 8?

SHARE:

A quick guide and understand how to compare two dates in java and new jdk i8 with example programs.

1. Overview

In this article, You'll learn how to compare two dates in java and also how to compare the dates in java 8.

Dates comparison means checking whether the date 1 is after date 2 or which one is older or future date.

First let us look into the older java api in java 7 and next exploring the different options with JDK 8.

If-else condition example

2. Comparing Two Dates 

First, Let us create two Date objects in format of "yyyy-MM-dd" using SimpleDateFormat.parse() method.

Next, use compareTo() method to compare the dates. compareTo() method returns integer value. 

  • If the returned value is 0, it means both dates are same. 
  • If the value > 0 then date 1 is after date 2.
  • if the value < 0 then date 1 is before date 2.

package com.javaprogramto.java8.dates.compare;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Example program to compare two dates in java
 * 
 * @author JavaProgramTo.com
 *
 */
public class DateCompareBeforeJava8 {

	public static void main(String[] args) throws ParseException {
		// Date format
		String DATE_FORMAT = "yyyy-MM-dd";
		
		// Creating an object for SimpleDateFormat
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
		
		// Date 1 created from string using SimpleDateFormat
		Date date1 = sdf.parse("2021-01-01");

		// Date 2 created from string using SimpleDateFormat
		Date date2 = sdf.parse("2021-02-01");
		
		// comparing two dates
		int dateOrder = date1.compareTo(date2);
		
		// printing the date comparison value returned by compareTo() method
		System.out.println("Dates comparision value : "+dateOrder);
		
		// Deciding the dates order.
		if(dateOrder == 0) {
			System.out.println("Date 1 and Date 2 are equal.");
		} else if(dateOrder > 0) {
			System.out.println("Date 1 is after Date 2.");
		} else {
			System.out.println("Date 1 before Date 2");
		}
	}
}

Output:

Dates comparision value : -1
Date 1 before Date 2

In the above example code, We called date1.compareTo(date2) and it returned value -1. So, it is indicating date 1 is older than date 2. Finally, it has executed else block.

If you swap the dates the it will say date 1 is after date 2.

3. Java 8 - Comparing Two Dates

Java 8 is added with lots of new features and DateTime api is one them.

There are mainly 3 classes added in java 8 to work with dates.

  • java.time.LocalDate
  • java.time.LocalDateTime
  • java.time.ZonedDateTime

Let us try to compare the same dates using java 8 api first with examples then we will understand when to which one from above three mostly used classes.

package com.javaprogramto.java8.dates.compare;

import java.text.ParseException;
import java.time.LocalDate;

/**
 * Example program to compare two dates in java 8 with LocalDate.
 * 
 * @author JavaProgramTo.com
 *
 */
public class DateCompareInJava8 {

	public static void main(String[] args) throws ParseException {
		
		// Creating first date using LocalDate.of() method.
		LocalDate date1 = LocalDate.of(2021, 01, 01);
		
		// Creating second date using LocalDate.of() method.
		LocalDate date2 = LocalDate.of(2021, 02, 01);
		
		// comparing dates with isEqual(), isAfter() and isBefore() methods.
		boolean isEqual = date1.isEqual(date2);
		boolean isAfter = date1.isAfter(date2);
		boolean isBefore = date1.isBefore(date2);
		
		// java 8 date comparisons results
		System.out.println("Date 1 and Date 2 are equals? : "+isEqual);
		System.out.println("Date 1 is after Date 2? : "+isAfter);
		System.out.println("Date 1 is before Date 2? : "+isBefore);
		

		// comparing two dates older way with compareTo() method.
		int dateOrder = date1.compareTo(date2);
		
		// printing the date comparison value returned by compareTo() method
		System.out.println("Dates comparision value with compareTo() returned value : "+dateOrder);
		
		// Deciding the dates order.
		if(dateOrder == 0) {
			System.out.println("Date 1 and Date 2 are equal.");
		} else if(dateOrder > 0) {
			System.out.println("Date 1 is after Date 2.");
		} else {
			System.out.println("Date 1 before Date 2");
		}

	}

}

Output:

Date 1 and Date 2 are equals? : false
Date 1 is after Date 2? : false
Date 1 is before Date 2? : true
Dates comparision value with compareTo() returned value : -1
Date 1 before Date 2

In the above example, we have used LocaleDate class methods isEqual(), isAfter() and isBefore() methods to compare the dates order.

If these methods returns true means that method condition is satisfied else not met the condition.

And alos still the new api has the compareTo() method to work with the older jdk.

4. Java 8 - Comparing Two Dates Along With Time Component

In java 8, LocalDate class compares only the dates and does not consider time part in the date. Other two classes such as LocalDateTime and ZonedDateTime work with date along with time. All 3 classes have isEqual(), isAfter() and isBefore() methods for dates comparisons.

Now, look at the date and time comparisons examples using LocalDateTime and ZonedDateTime classes.

LocalDateTime Example:

package com.javaprogramto.java8.dates.compare;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * Example program to compare two dates in java 8 with LocalDateTime.
 * 
 * @author JavaProgramTo.com
 *
 */
public class DateCompareLocalDateTimeInJava8 {

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

		// Creating first date using LocalDateTime.of() method.
		LocalDateTime datetime1 = LocalDateTime.of(2021, 02, 01, 01, 01, 01);

		// Creating second date using LocalDateTime.now() method with milliseconds.
		LocalDateTime datetime2 = LocalDateTime.now();

		// comparing dates with isEqual(), isAfter() and isBefore() methods.
		boolean isEqual = datetime1.isEqual(datetime2);
		boolean isAfter = datetime1.isAfter(datetime2);
		boolean isBefore = datetime1.isBefore(datetime2);

		// java 8 date comparisons results
		System.out.println("DateTime 1 and DateTime 2 are equals? : " + isEqual);
		System.out.println("DateTime 1 is after DateTime 2? : " + isAfter);
		System.out.println("DateTime 1 is before DateTime 2? : " + isBefore);
	}

}

Output:

DateTime 1 and DateTime 2 are equals? : false
DateTime 1 is after DateTime 2? : true
DateTime 1 is before DateTime 2? : false

ZonedDateTime Example:

package com.javaprogramto.java8.dates.compare;

import java.text.ParseException;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * Example program to compare two dates in java 8 with ZonedDateTime.
 * 
 * @author JavaProgramTo.com
 *
 */
public class DateCompareZonedDateTimeInJava8 {

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

		// Creating first date using ZonedDateTime.of() method with nano seconds and time zone id.
		ZonedDateTime zonesDatetime1 = ZonedDateTime.of(2021, 02, 01, 01, 01, 01, 1, ZoneId.systemDefault());

		// Creating second date using ZonedDateTime.now() method with milliseconds.
		ZonedDateTime zonedDatetime2 = ZonedDateTime.now();

		// comparing dates with isEqual(), isAfter() and isBefore() methods.
		boolean isEqual = zonesDatetime1.isEqual(zonedDatetime2);
		boolean isAfter = zonesDatetime1.isAfter(zonedDatetime2);
		boolean isBefore = zonesDatetime1.isBefore(zonedDatetime2);

		// java 8 date comparisons results
		System.out.println("ZonedDateTime 1 and ZonedDateTime 2 are equals? : " + isEqual);
		System.out.println("ZonedDateTime 1 is after ZonedDateTime 2? : " + isAfter);
		System.out.println("ZonedDateTime 1 is before ZonedDateTime 2? : " + isBefore);
	}

}

Output:

ZonedDateTime 1 and ZonedDateTime 2 are equals? : false
ZonedDateTime 1 is after ZonedDateTime 2? : true
ZonedDateTime 1 is before ZonedDateTime 2? : false

5. Conclusion

In this tutorial, you've seen how to compare two dates in java 8 and older java versions and differences among java 8 date classes,

  • java.time.LocalDate
  • java.time.LocalDateTime
  • java.time.ZonedDateTime

GitHub

DateCompareBeforeJava8

DateCompareInJava8

DateCompareLocalDateTimeInJava8

DateCompareZonedDateTimeInJava8

Read Next:

java.util.Date Examples

How to use MinguoDate in java 8?

Java 8 TemporalAdjusters

Java 8 new features indepth

API:

LocalDate  LocalDateTime  ZonedDateTime


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,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,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,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: How To Compare Two Dates In Java and New Java 8?
How To Compare Two Dates In Java and New Java 8?
A quick guide and understand how to compare two dates in java and new jdk i8 with example programs.
JavaProgramTo.com
https://www.javaprogramto.com/2020/11/how-to-compare-two-dates-in-java-and.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/11/how-to-compare-two-dates-in-java-and.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