×

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we may utilise built-in Java methods from the Date class, the Calendar class, and the LocalDate class. Additionally, we have access to other libraries like Date4j, DateUtils, and Jodatime. Let's talk about how to compare dates:

We'll be using :

after(), before() and equals() methods of the Date class

Date.compareTo() method from the class Date.

after(), before(), equals(), getInstance() and setTime() using Calendar Class methods

isAfter(), isBefore(), isEqual() and compareTo() methods from the LocalDate Class

Java's Date Class may be used to compare two dates.

Java's Date class has several helpful methods, including before(), after(), and equals (). By using these functions, we may compare two dates.

We must import the following to use these functions:

  • Date taken from the utility package
  • SimpleDateFormat is a text package component.
  • The text package's ParseException

Let's explore in some more details about these functions:

after():

Syntax: date1.after(date2)

Return Type: Boolean If date1 exactly matches date2 then this method returns true, else it returns false. It returns false even if the dates are same.

before():

Syntax: date1.before(date2)

Return Type: Boolean If date1 occurs before date2, this function returns true; else, it returns false. It returns false even if the dates are same.

equals():

Synax: date1.equals(date2)

Return Type: Boolean If date1 and date2 are equal, this method returns true; else, it returns false. The equals() function of the Date class compares the number of milliseconds since January 1st, 1970, 00:00:00 GTM to determine if two values are equal. The getTime() method assist in the accomplishment of this. The long data type that the getTime() method returns is the number of milliseconds.

We'll utilise the SimpleDateFormat class object to store dates. This will enable us to specify the date's format.

Syntax: SimpleDateFormat(String format)

The format string in the SimpleDateFormat object's parameter should include the pattern that will be used to parse the date string.

String example:

String fr = "dd/MM/yyyy";

Parsing syntax:

obj.parse(Date)

We would need to follow the following packages in order to use the Date Class in Java:

  • Date taken from the utility package
  • SimpleDateFormat is a text package component.
  • Text package ParseException

DateCompareUsingDateClass.java

import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;


public class DateCompareUsingDateClass
{
    public static void main(String[] args) throws ParseException
    {
        // Object of the SimpleDateFormat class
        SimpleDateFormat dtobj = new SimpleDateFormat("dd/MM/yyyy");
        // Dates
        String dp = "26/12/2022";
        String dq = "19/06/2022";
        // In the Date datatype, parsing dates
        Date p = dtobj.parse(dp);
        Date q = dtobj.parse(dq);
        // Dates are being printed
        System.out.println("Date p is " + dtobj.format(p));
        System.out.println("Date q is " + dtobj.format(q));
        // Searching for equal cases
        if (p.equals(q))
            System.out.println("Both dates are for the same day.");
        // Searching for after cases
        else if (p.after(q))
            System.out.println("Date p comes after Date q");
        // Searching for before cases
        else if (p.before(q))
            System.out.println("Date p comes before Date q");
    }
}

Output:

How to compare two dates in different format in Java

Explanation:

Here, we're developing a SimpleDateFormat object that will enable us to transform dates that are provided as strings to dates of the "Date" type. Utilizing the parse method of the SimpleDateFormat class, we will convert. Then, to compare the provided dates, we use the equals(), after(), and before() methods.

Using SimpleDateFormat Class

Because now we know how to alter the date format from dd/MM/yyyy to dd MMM yyyy, let's look at the appropriate code.

DateChangeUsingSimpleDateFormat.java

import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class DateChangeUsingSimpleDateFormat
{
    public static void main(String[] args) throws ParseException
    {
        // Object of the SimpleDateFormat class
        SimpleDateFormat dtobj = new SimpleDateFormat("dd/MM/yyyy");
        String d = "21/12/2022";
        // Parsing data using the Date datatype
        Date a = dtobj.parse(d);
        // printing in the same style
        System.out.println("Date is " + dtobj.format(a));
        // Format modification
        SimpleDateFormat fr = new SimpleDateFormat("dd MMM yyyy");
        // Printing in new format
        System.out.println("New format for the date is " + fr.format(a));
    }
}

Output:

How to compare two dates in different format in Java

Explanation:

In this case, we're making two Simple Date Format objects: one to convert the provided date from String to Date type, and the other to format it in the new format.

Using Date.compareTo() Method

To compare the two dates, we may utilise the compareTo() method from the Date class.

The method compareTo() obtains:

  • 0 if the dates are equal
  • 1 if date1 comes after date 2
  • -1 if date1 occurs before date2

Syntax:

date1.compareTo(date2)

Returns: Integer

To use Date.compareTo(), we must import the following:

  • Date taken from the utility package
  • SimpleDateFormat is a text package component.
  • A parse error occurred in the text package

Comparedates.java

import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;


public class Comparedates
{
    public static void main(String[] args) throws ParseException
    {
        // Object of the SimpleDateFormat class
        SimpleDateFormat dtobj = new SimpleDateFormat("dd/MM/yyyy");
        // Dates
        String dp = "15/09/2012";
        String dq = "27/12/2022";
        //Date datatype parsing of dates
        Date p = dtobj.parse(dp);
        Date q = dtobj.parse(dq);
        // Dates are being printed
        System.out.println("Date p is " + dtobj.format(p));
        System.out.println("Date q is " + dtobj.format(q));
        // Calculating the number of days that separate two dates
        int difference = p.compareTo(q);
        if (difference == 0)
            System.out.println("Both dates are of equal");
        else if (difference == 1)
            System.out.println("Date p comes after Date q");
        else if (difference == -1)
            System.out.println("Date p comes before Date q");
    }
}

Output:

How to compare two dates in different format in Java

Explanation:

Here, we convert the provided dates from the String type to the Date type using the SimpleDateFormat object, and then we compare the dates using the compareTo() function of the Date class.

Using Java Calendar Class

The Date class evaluates the difference between the two dates with respect to a fixed instance of time. While the difference between the two dates is immediately calculated by the Calendar class

We need to initialise 2 variables with the getInstance() function in order to utilise the Calendar class in Java. Utilising Locale and Timezone, getInstance() gets the current date and time. We'll make use of the setTime() method to set the dates. The necessary date is set using setTime(). The calendar class uses milliseconds to compare time.

Syntax:

Calendar obj = Calendar.getInstance();
obj.setTime(Date);

In order to use the Calendar class, we must import:

  • Calendar from the utility package.
  • SimpleDateFormat is a text package component.
  • The text package's ParseException

CompareDate.java

import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.text.ParseException;


public class CompareDate
{
    public static void main(String[] args) throws ParseException
    {
        // Object of the SimpleDateFormat class
        SimpleDateFormat dtobj = new SimpleDateFormat("dd/MM/yyyy");
        // Dates
        String dp = "15/09/2003";
        String dq = "25/12/2022";
        // Dates are being printed
        System.out.println("Date p is " + dtobj.format(dtobj.parse(dp)));
        System.out.println("Date q is " + dtobj.format(dtobj.parse(dq)));
        // using getInstance to set up two variables
        Calendar w1 = Calendar.getInstance();
        Calendar w2 = Calendar.getInstance();
        // modifying the dates
        w1.setTime(dtobj.parse(dp));
        w2.setTime(dtobj.parse(dq));
        // Checking for equal case
        if (w1.equals(w2))
            System.out.println("Both dates are equal");
        // Checking for after case
        else if (w1.after(w2))
            System.out.println("Date p comes after Date q");
        // Checking for before case
        else if (w1.before(w2))
            System.out.println("Date p comes before Date q");
    }
}

Output:

How to compare two dates in different format in Java

Explanation:

To parse the dates in this instance, we are utilising a SimpleDateFormat object. The date is then printed using the format() and parse() functions. Two Calendar variables have been initialised using the getInstance() method. They are initialised with the current time using getInstance(). Then, to store the provided dates, we utilised the setTime() method. Using the equals(), after(), and before() methods of the Calendar class, we compare the dates at the end.

Compare two dates in Java Using the LocalDate Class

It is used to display local dates without regard to time or zone. Since we do not need to give a time or zone, it is used in those circumstances. It is suitable for keeping dates of significant occurrences (for instance, class attendance) or comparing two dates. Instances of LocalDate are immutable, so that once they are generated, they cannot be modified.

In the LocalDate Class, there are functions like isAfter(), isBefore(), isEqual(), and compareTo(). The methods after(), before(), and equals() of the Calendar and Date class are very similar to isAfter(), isBefore(), and isEqual().

Dates are formatted as yyyy-MM-dd by default. By using the DateTimeFormatter() class and parsing the LocalDate class method, we may modify the format.

Syntax:

DateTimeFormatter obj = DateTimeFormatter.ofPattern(String);

Comparedates.java

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.text.ParseException;
public class Comparedates
{
    public static void main(String[] args) throws ParseException
    {
        // Object of class DateTimeFormatter
        DateTimeFormatter dtobj = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        // Dates
        String dp = "15/01/1942";
        String dq = "25/12/2022";
        // interpreting the dates
        LocalDate ldp = LocalDate.parse(dp, dtobj);
        LocalDate ldq = LocalDate.parse(dq, dtobj);
        // Dates being printed
        System.out.println("Date p is " + dtobj.format(ldp));
        System.out.println("Date q is " + dtobj.format(ldq));
        // Checking for equal case
        if (ldp.isEqual(ldq))
            System.out.println("Both dates are equal");
        // Checking for after case
        else if (ldp.isAfter(ldq))
            System.out.println("Date p comes after Date q");
        // Checking for before case
        else if (ldp.isBefore(ldq))
            System.out.println("Date p comes before Date q");
    }
}

Output:

How to compare two dates in different format in Java

Explanation:

To convert the provided dates from String type to LocalDate type in this case, we are using DateTimeFormatter object. Then, to compare the provided dates, we use the isEqual(), isAfter(), and isBefore() methods.


Related Topics

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Types of Sockets in Java

The fundamental idea behind Java's networking capability is the socket. Early in the 1980s, the Berkeley UNIX 4.2BSD version included the socket paradigm. Berkeley socket is the term employed as...

9 minutes read.

Java Binary Tree

The non-linear data structure known as a binary tree is a type of tree, and because it stores data in a hierarchical manner, it is mostly utilised for finding and...

7 minutes read.

Armstrong Number Program in Java

Armstrong Number Program in Java: A positive number is called an Armstrong number if the sum of the cube of each digit is equal to the number itself. There are...

6 minutes read.

Types of Bitwise Operators in Java

In this tutorial, we will learn about the various types or kinds of bitwise operators in java. Before proceeding to bitwise operators, let us know what is meant by the...

6 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Java Math min() Method

The min() method of Math class returns the smaller of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double min (double a, double...

2 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

Java Math sin() Method

The sin() method of Java Math class returns the trigonometric sine of the specified angle. Syntax: public static double sin(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The sin() method...

1 minute read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

How to generate random numbers in Java

Random numbers, also known as fake numbers, are actually a part of a very large sequence, so they are called random numbers. In a defined set of numbers, every number...

6 minutes read.