
- Java Tutorial
- Java - Home
- Java - Overview
- Java - Environment Setup
- Java - Basic Syntax
- Java - Object & Classes
- Java - Constructors
- Java - Basic Datatypes
- Java - Variable Types
- Java - Modifier Types
- Java - Basic Operators
- Java - Loop Control
- Java - Decision Making
- Java - Numbers
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Regular Expressions
- Java - Methods
- Java - Files and I/O
- Java - Exceptions
- Java - Inner classes
- Java Object Oriented
- Java - Inheritance
- Java - Overriding
- Java - Polymorphism
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java Advanced
- Java - Data Structures
- Java - Collections
- Java - Generics
- Java - Serialization
- Java - Networking
- Java - Sending Email
- Java - Multithreading
- Java - Applet Basics
- Java - Documentation
- Java Useful Resources
- Java - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
How to compare two dates in Java?
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
Syntax
int compareTo(T o)
Example
import java.text.*; import java.util.Date; public class CompareTwoDatesTest { public static void main(String[] args) throws ParseException { SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd"); Date d1 = sdformat.parse("2019-04-15"); Date d2 = sdformat.parse("2019-08-10"); System.out.println("The date 1 is: " + sdformat.format(d1)); System.out.println("The date 2 is: " + sdformat.format(d2)); if(d1.compareTo(d2) > 0) { System.out.println("Date 1 occurs after Date 2"); } else if(d1.compareTo(d2) < 0) { System.out.println("Date 1 occurs before Date 2"); } else if(d1.compareTo(d2) == 0) { System.out.println("Both dates are equal"); } } }
In the above example, the date d1 occurs before the date d2, so it can display "Date 1 occurs before Date 2" in the console.
Output
The date 1 is: 2019-04-15 The date 2 is: 2019-08-10 Date 1 occurs before Date 2
- Related Articles
- How to compare two dates in String format in Java?
- How to compare two dates along with time in Java?
- How to compare two Dates in C#?
- How to compare two dates with JavaScript?
- Compare Dates in Java
- PHP program to compare two dates
- How to compare dates in JavaScript?
- What are various ways to compare dates in Java?
- How to Compare two String in Java?
- How to compare two arrays in Java?
- How to count days between two dates in Java
- How do we compare Python Dates?
- How to compare two ArrayList for equality in Java?
- How to list all dates between two dates in Excel?
- How to get number of quarters between two dates in Java

Advertisements