In this example you’ll see the utilization of SimpleDateFormat
class for comparing two dates for equality. We convert the date object into string using the DateFormat
instance and then compare it using String.equals()
method.
package org.kodejava.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class ComparingDate {
public static void main(String[] args) {
// Create a SimpleDateFormat instance with dd/MM/yyyy format
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
// Get the current date
Date today = new Date();
// Create an instance of calendar that represents a new year date
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DATE, 1);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.YEAR, 2021);
String newYear = df.format(calendar.getTime());
String now = df.format(today);
// Using the string equals method we can compare the date.
if (now.equals(newYear)) {
System.out.println("Happy New Year!");
} else {
System.out.println("Have a nice day!");
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024