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:
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:
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:
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:
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:
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.