I am trying to compare dates from two object having different types. Is there any way to convert Calendar object to LocalDater or vice-versa?
Thank you :)
public class ABC{
public static void main(String args[]){
Calendar c1= Calendar.getInstance();
LocalDate c2= LocalDate.now();
System.out.println(c1.compareTo(c2));
}
}
Two LocalDate objects can be compared using the compareTo() method in the LocalDate class in Java. This method requires a single parameter i.e. the LocalDate object to be compared.
LocalDateTime instances contain the date as well as the time component. Similarly to LocalDate, we're comparing two LocalDateTime instances with the methods isAfter(), isBefore() and isEqual(). Additionally, equals() and compareTo() can be used in a similar fashion as described for LocalDate.
Calendar compareTo() Method in Java with Examples The method returns 0 if the passed argument is equal to this Calendar object. The method returns 1 if the time of this Calendar object is more than the passed object. The method returns -1 if the time of this Calendar object is less than the passed object.
You need to compare dates, so let's do just that.
Using this answer as reference:
Calendar calendar = Calendar.getInstance();
LocalDate localDate = LocalDate.now();
LocalDate calendarAsLocalDate = calendar.toInstant()
.atZone(calendar.getTimeZone().toZoneId())
.toLocalDate();
return calendarAsLocalDate.compareTo(localDate)
private int compare(Calendar c1, LocalDate c2) {
int yearCompare = ((Integer) c1.get(Calendar.YEAR)).compareTo(c2.getYear());
if (yearCompare == 0)
return ((Integer) c1.get(Calendar.DAY_OF_YEAR)).compareTo(c2.getDayOfYear());
else
return yearCompare;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With