.equals()
Published Aug 20, 2023
Contribute to Docs
The .equals()
method of the Date
class compares the current Date
object to the specified object. It will return true
if the dates are equal (differences evaluated down to the millisecond). Otherwise, it returns false
.
Syntax
dateOne.equals(dateTwo)
Note: The return type of the method is
boolean
so this method will return eithertrue
orfalse
.
Example
In this example, the JavaDateEqualsExample
class demonstrates the use of .equals()
.
import java.util.Date;public class JavaDateEqualsExample {public static void main(String[] args) {// Create a new date objectDate dateOne = new Date();// Print the current date and timeSystem.out.println("first date object - current date and Time : " + dateOne);// Create a second date objectDate dateTwo = new Date();// Print second date objectSystem.out.println("second date object - current date and Time : " + dateTwo);// Compare the first and second date object using equals() methodboolean dateEqual = dateOne.equals(dateTwo);// Print the resultSystem.out.println("first date object and second date object are equal: " + dateEqual);}}
This code will return an output similar to the following:
first date object - current date and Time : Fri Aug 18 22:55:26 IST 2023second date object - current date and Time : Fri Aug 18 22:55:26 IST 2023first date object and second date object are equal: false
Note: The output of the above example is
false
because the method considers differences down to the millisecond.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours