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.example.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, 2017);
String now = df.format(today);
String newYear = df.format(calendar.getTime());
// 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!");
}
}
}
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I set the time of java.util.Date instance to 00:00:00? - October 24, 2019
- How to Install Consolas Font in Mac OS X? - March 29, 2019
- How do I clear the current command line in terminal? - February 14, 2019