HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Date Time / Java – Date Comparison

Java – Date Comparison

Learn to compare dates in Java. We will see the examples of date comparison using Date and Calendar (till Java 7); LocalDate, LocalDateTime and ZonedDateTime classes from Java 8.

1. Date Comparison in Java 8

1.1. Date Time Classes

The most used date classes in Java 8 are:

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

1.2. Comparison Methods

All above classes have methods for comparing two instances of themselves i.e. isAfter(), isBefore(), isEqual() and compareTo().

  1. date1.isAfter( date2 ) – It returns true is date1 comes after date2; else false.
  2. date1.isBefore( date2 ) – It returns true is date1 comes before date2; else false.
  3. date1.isEqual( date2 ) – It returns true is date1 is equal to date2; else false.
  4. date1.compareTo( date2 ) – It returns ‘positive number’ is date1 comes after date2; else ‘negative number’. A value '0' means both dates are equal.

Note : If you only want to compare date part and do not care about which part of time it is – then use LocalDate instances. LocalDateTime and ZonedDateTime compare time part as well, so even if the day they represent is same calendar day, if time is not same then they are not equal.

Use toLocalDate() to get the date part from LocalDateTime and ZonedDateTime instances.

1.3. Example Code

import java.time.LocalDate;
import java.time.LocalDateTime;

public class DateComparison 
{
	public static void main(String[] args) throws InterruptedException 
	{
		LocalDate today = LocalDate.now();
	    LocalDate anotherDay = LocalDate.of(2018, 01, 10);
	    
	    System.out.println(today.isEqual(anotherDay));		//false
	    System.out.println(today.isAfter(anotherDay));		//true
	    System.out.println(today.isBefore(anotherDay));		//false
	    
	    int diff = today.compareTo(anotherDay);
        if(diff > 0) {
            System.out.println(today + " is greater than " + anotherDay);
        } else if (diff < 0) {
            System.out.println(today + " is less than " + anotherDay);
        } else {
            System.out.println(today + " is equal to " + anotherDay);
        }
        
        //LocalDateTime and ZonedDateTime use time part as well during comparison
        
        //Both instances are on same day but time is 100 milliseconds off
        //They are not equal during comparison
        
        LocalDateTime instance = LocalDateTime.now();
        Thread.currentThread().sleep(100);
        LocalDateTime anotherInstance = LocalDateTime.now();
        
        System.out.println(instance.isEqual(anotherInstance));		//false
        System.out.println(instance.isAfter(anotherInstance));		//false
	    System.out.println(instance.isBefore(anotherInstance));		//true
	    
	    //Compare only date part from LocalDateTime
	    
	    System.out.println(
	    		instance.toLocalDate().isEqual(anotherInstance.toLocalDate()));	//true
	}
}

2. Date Comparison till Java 7

2.1. Date Classes

The most used date classes till Java 7 were:

  • java.util.Date
  • java.util.Calendar

2.2. Comparison Methods

Both, Date and Calendar classes have methods before(), after() and equals() methods for date comparison purpose.

  1. date1.after( date2 ) – It returns true is date1 comes after date2; else false.
  2. date1.before( date2 ) – It returns true is date1 comes before date2; else false.
  3. date1.equals( date2 ) – It returns true is date1 and date2 are equal; else false.
  4. date1.compareTo( date2 ) – It returns ‘positive number’ is date1 comes after date2; else ‘negative number’. A value '0' means both dates are equal.

Note: Both, Date and Calendar classes have time part and above methods use it for comparing. So, if you want to compare only date part and do not care time part of it, then you need to extract day/month/year from other instances are compare then one to one.

2.3. Example Code

In the given code, we first compare the two date instances including their time part. Then we compare them only their date part excluding any time part associated with instances.

//Comparing two date instances along with time

Date date1 = new Date();

//To have different time part in both instances
Thread.currentThread().sleep(100);	

Date date2 = new Date();

System.out.println(date1.equals(date2));		//false
System.out.println(date1.after(date2));			//false
System.out.println(date1.before(date2));		//true

//Comparing two date instances - only date part and ignore time part

//date1 and date2 are on same day
System.out.println("Date part comparison result :: " 
		+ compareDatePartOnly(date1, date2));

//date1 and date2 are on different day
System.out.println("Date part comparison result :: " 
		+ compareDatePartOnly(new Date(2020,2,3), new Date(2020,3,4)));



/*
* @return 0 if date1 and date2 falls on same day
* 	       negative (-) value if date2 is greater
* 		   positive (+) value if date1 is greater  
*/
private static int compareDatePartOnly(Date date1, Date date2)
{
	Calendar cal1 = Calendar.getInstance();
	Calendar cal2 = Calendar.getInstance();

	cal1.setTime(date1);
	cal2.setTime(date2);

	int result = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);

	if(result == 0)
	{
		result = cal1.get(Calendar.DAY_OF_YEAR) - cal2.get(Calendar.DAY_OF_YEAR);
	} 
		    
	return result;
}

Drop me your questions related to comparing dates in Java.

Happy Learning !!

Sourcecode Download

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Java Date Time Tutorial

  • Java – Date Time APIs
  • Java – Date Parsing
  • Java – Date Formatting
  • Java 8 – LocalDate
  • Java 8 – LocalTime
  • Java 8 – LocalDateTime
  • Java 8 – ZonedDateTime
  • Java 8 – Period
  • Java 8 – DateTimeFormatter
  • Java 8 – TemporalAdjusters
  • Java 8 – TemporalQuery
  • Java 8 – DayOfWeek
  • Java – Date
  • Java – Locale

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces