Home » Java programming language

Java Date compareTo() Method with Example

Date Class compareTo() method: Here, we are going to learn about the compareTo() method of Date Class with its syntax and example.
Submitted by Preeti Jain, on February 09, 2020

Date Class compareTo() method

  • compareTo() method is available in java.util package.
  • compareTo() method is used to compare this date and the given date (d2) or in other words, we can this method compare two Date objects.
  • compareTo() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • compareTo() method may throw an exception at the time of comparing two Date objects.
    NullPointerException: This exception may throw when the given parameter (d2) is null exists.

Syntax:

    public int compareTo(Date d2);

Parameter(s):

  • Date d2 – represents another date to be compared with.

Return value:

The return type of this method is int, it returns any one of the given values.

  • It returns 0, when d1 = d2.
  • It returns negative value, when d1 < d2.
  • It returns positive value, when d1 > d2.

Example:

// Java program to demonstrate the example 
// of int compareTo() method of Date

import java.util.*;

public class CompareToDate {
    public static void main(String[] args) {
        // create two Date object with two dates
        Date this_date = new Date(2016, 8, 20);
        Date given_date = new Date(2010, 11, 30);

        // By using compareTo() method is to compare
        // this_date and the given_date
        int result = this_date.compareTo(given_date);

        // Display result
        System.out.println("this_date.compareTo(given_date): " + result);
    }
}

Output

this_date.compareTo(given_date): 1


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.