Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare objects of LocalDate and Calendar class?

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));
    }
}
like image 434
Maulik Doshi Avatar asked Apr 14 '17 13:04

Maulik Doshi


People also ask

How do LocalDate objects compare?

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.

Can we compare LocalDate and date in Java?

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.

How do I compare two instances of Java calendar?

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.


2 Answers

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)
like image 121
Olivier Grégoire Avatar answered Nov 02 '22 17:11

Olivier Grégoire


    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;
    }
like image 34
Jeff Avatar answered Nov 02 '22 17:11

Jeff