ClassCastException when comparing Dates?

99封情书 提交于 2019-12-11 09:50:01

问题


I am using GXT/ExtGWT. I have below code which compares two dates.

private DateField startDateField = new DateField();
private DateField endDateField = new DateField();
Date date = new Date();

CalendarUtil.addDaysToDate(date, -1);
startDateField.setValue(date);
endDateField.setValue(new Date());

Date fromDate = startDateField.getValue();
Date toDate = endDateField.getValue();    

Date differenceBetweenDates = new Date(fromDate.getTime());
CalendarUtil.addMonthsToDate(differenceBetweenDates, 6);

if (differenceBetweenDates.before(toDate)) {
    MessageBox.alert("Alert","Date range should not exceed six months", null);
    return false;
} else{ 
    return true;
}

Here in datefields fromdate I selected as 0012-12-30 and todate as 0012-12-31.

When the line differenceBetweenDates.before(toDate) is executed, I am getting below exception. Please help me. Am i doing any wrong here?

java.lang.ClassCastException: sun.util.calendar.JulianCalendar$Date cannot be cast to sun.util.calendar.Gregorian$Date

回答1:


According to http://www.docjar.com/html/api/java/util/Date.java.html, java.util.Date contains this code:

private static final BaseCalendar getCalendarSystem(long utc) {
  // Quickly check if the time stamp given by `utc' is the Epoch
  // or later. If it's before 1970, we convert the cutover to
  // local time to compare.
  if (utc >= 0
    || utc >= GregorianCalendar.DEFAULT_GREGORIAN_CUTOVER
        - TimeZone.getDefaultRef().getOffset(utc)) {
    return gcal;
 }
 return getJulianCalendar();

}

So it looks to me that because you are putting year in as 0012 not 2012, it chooses JulianCalendar.




回答2:


I have the same problem, but for a different use case (the Dates do come from user input, yet the data source is an Excel table).

A very simple workaround did the trick for me:

private static boolean isBefore(Date firstDate, Date secondDate) {
    return firstDate.getTime() < secondDate.getTime();
}



回答3:


Your date parsing has some problem. Something thinks you intend to represent time according to Caesar's Julian calendar! Unless you're Orthodox I doubt this is the intent. endDateField has some problem inside that is manipulating dates with the entirely wrong calendar.



来源:https://stackoverflow.com/questions/8831545/classcastexception-when-comparing-dates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!