My requirement is to compare a given date in a particular format in a given timezone to the current date in the same time zone. Also while comparing I have to ignore the timezone. And the comparison result should be: 0 or 1 or -1
One way I have tried is
- Set the required timezone
- Get the current date using "new Date()" format it using "yyyy-MM-dd" and then parse it again to get the date object
- Use the same formatter for supplied date string to be compared
- Then compare both dates using compareTo which gives the desired result
public void compareDate(){
TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
Date todayDate = dateFormatter.parse(dateFormatter.format(new Date()));
Date date = dateFormatter.parse("2021-02-28");
System.out.println(todayDate.compareTo(date));
}
But the above looks inefficient to me.
Other way could be to get both the dates like below and then compare?
public static Date getDateWithoutTimeUsingCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
Can someone please suggest a better alternative?
Just one thing, timezone and comparing without time has to be there.