ADVERTISEMENT
ADVERTISEMENT

Java program to compare dates using Date.compareTo() method

Learn how to compare dates using Date.compareTo() method in Java?
Submitted by Nidhi, on March 31, 2022

Problem Solution:

Given two dates, we have to compare them. We will create objects of the Date class with specified dates. Then we will compare using the Date.compareTo() method.

Program/Source Code:

The source code to compare dates using the Date.compareTo() method is given below. The given program is compiled and executed successfully.

// Java program to compare dates using 
// Date.compareTo() method

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Date date1 = new Date(22, 9, 16);
    Date date2 = new Date(21, 10, 15);
    Date date3 = new Date(21, 10, 15);

    int result = 0;

    result = date1.compareTo(date2);
    if (result > 0)
      System.out.println("The date1 is later than date2");
    else if (result < 0)
      System.out.println("The date2 is later than date1");
    else
      System.out.println("Both are equal");

    result = date2.compareTo(date3);
    if (result > 0)
      System.out.println("The date2 is later than date3");
    else if (result < 0)
      System.out.println("The date3 is later than date2");
    else
      System.out.println("Both are equal");
  }
}

Output:

The date1 is later than date2
Both are equal

Explanation:

In the above program, we imported the "java.util.*" package to use the Date class. Here, we created a class Main that contains a static method main(). The main() method is the entry point for the program, here we created three objects of the Date class with specified dates. Then we compared created objects using the compareTo() method and printed appropriate messages.

Java Date and Time Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.