×

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

MOOD Factors to Assess a Java Program

In this tutorial, we will comprehendthe meaning of mood factors in Java. For the development of any software system,the quality of anapplication is important. It is more important to maintain large-scale...

4 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To...

4 minutes read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Finding middle node of a linked list in Java

To find the middle node of a linked list we have various methods in Java. Method 1 In this method two pointers are used, one of which advances quickly, and the other of...

6 minutes read.

How to Convert Hexadecimal to Decimal in Java

How to Convert Hexadecimal to Decimal in Java There are two methods to convert Hexadecimal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method It is a static method of...

2 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.