如何比较 LocalDate 和 Calendar class 的对象?
How to compare objects of LocalDate and Calendar class?
我正在尝试比较两个具有不同类型的对象的日期。有什么方法可以将 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));
}
}
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;
}
您需要比较日期,所以我们就这样做吧。
使用this answer作为参考:
Calendar calendar = Calendar.getInstance();
LocalDate localDate = LocalDate.now();
LocalDate calendarAsLocalDate = calendar.toInstant()
.atZone(calendar.getTimeZone().toZoneId())
.toLocalDate();
return calendarAsLocalDate.compareTo(localDate)
我正在尝试比较两个具有不同类型的对象的日期。有什么方法可以将 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));
}
}
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;
}
您需要比较日期,所以我们就这样做吧。
使用this answer作为参考:
Calendar calendar = Calendar.getInstance();
LocalDate localDate = LocalDate.now();
LocalDate calendarAsLocalDate = calendar.toInstant()
.atZone(calendar.getTimeZone().toZoneId())
.toLocalDate();
return calendarAsLocalDate.compareTo(localDate)