8

我正在尝试比较两个具有不同类型的对象的日期。有没有办法将 Calendar 对象转换为 LocalDater 或反之亦然?

谢谢 :)

public class ABC{

    public static void main(String args[]){
        Calendar c1= Calendar.getInstance();
        LocalDate c2= LocalDate.now();      
        System.out.println(c1.compareTo(c2));
    }
}
4

2 回答 2

5

您需要比较dates,所以让我们这样做。

使用此答案作为参考:

Calendar calendar = Calendar.getInstance();
LocalDate localDate = LocalDate.now();

LocalDate calendarAsLocalDate = calendar.toInstant()
    .atZone(calendar.getTimeZone().toZoneId())
    .toLocalDate();

return calendarAsLocalDate.compareTo(localDate)
于 2017-04-14T14:06:12.287 回答
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;
    }
于 2017-04-14T13:50:57.370 回答