我正在尝试计算自特定日期起经过的月份,但如果我将今天的日期与过去的年份不同,则该函数可以使我有一个月的差异(少于一个月),因此该函数可以正常工作。
说出所有日期,该功能运行良好,但以下情况除外:
如果今天是“ 2014-03-06”(YYYY,MM,DD),并且我将函数的日期处理为“ 2006-03-06”,则结果要短一个月,但是如果明天使用相同的日期,结果很好。我要去哪里错了。下面是代码:
public static int months(String d) { SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd"); Date d1 = null; try { d1 = f.parse(d); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Date d2 = (getCurrentDate()); Date d2 = getCurrentDate(); Calendar c1 = Calendar.getInstance(); c1.setTime(d1); Calendar c2 = Calendar.getInstance(); c2.setTime(d2); int diff = 0; if (c2.after(c1)) { while (c2.after(c1)) { c1.add(Calendar.MONTH, 1); if (c2.after(c1)) { diff++; } } } else if (c2.before(c1)) { while (c2.before(c1)) { c1.add(Calendar.MONTH, -1); if (c1.before(c2)) { diff--; } } } System.out.println(diff); return diff; }
请不要考虑函数的静态性质,出于测试目的,我已将此代码隔离在其他项目中。
这是c1和c2的值:
java.util.GregorianCalendar[time=1141583400000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Kolkata",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2006,MONTH=2,WEEK_OF_YEAR=10,WEEK_OF_MONTH=2,DAY_OF_MONTH=6,DAY_OF_YEAR=65,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=19800000,DST_OFFSET=0] and c2 is: java.util.GregorianCalendar[time=1394044200000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Kolkata",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=2,WEEK_OF_YEAR=10,WEEK_OF_MONTH=2,DAY_OF_MONTH=6,DAY_OF_YEAR=65,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=19800000,DST_OFFSET=0] 95
我这里不好的是getCurrentDate():
public static Date getCurrentDate() { String DateStr = new SimpleDateFormat("yyyy-MM-dd"/*, current*/).format(Calendar.getInstance().getTime()); // String DateStr = formattedDate; Date date = null; try { date = new SimpleDateFormat("yyyy-MM-dd"/*, current*/).parse(DateStr); } catch (ParseException e) { e.printStackTrace(); } java.sql.Date dx = new java.sql.Date(date.getTime()); return dx; }
检查您的getCurrentDate()方法。我已替换为new Date(),输出96如您所说。
getCurrentDate()
new Date()
96