8

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
  • 529
  • 5
  • 19
Maulik Doshi
  • 315
  • 1
  • 11

2 Answers2

5

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
  • 28,397
  • 21
  • 84
  • 121
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,656
  • 1
  • 14
  • 27
  • 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