9

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));
    }
}
HessianMad
  • 549
  • 7
  • 23
Maulik Doshi
  • 323
  • 2
  • 11

2 Answers2

6

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)
Community
  • 1
  • 1
Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
1
    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;
    }
Jeff
  • 1,871
  • 1
  • 17
  • 28
  • You can do comparisons of int values by simply subtracting them. For instance, `int yearCompare = c1.get(Calendar.YEAR) - c2.getYear();`. This works even when there is integer overflow, due to the nature of twos-complement representation. – VGR Apr 14 '17 at 14:06