二个日期相隔天数的问题,错在哪里?
public int Get_Date_Count(String startDate,String endDate,int flag)
{
SimpleDateFormat sf=new SimpleDateFormat( "yyyyMMdd ");
Date sDate = new Date();
Date eDate = new Date();
sDate = sf.parse(startDate);//Unhandled exception type
ParseException eDate=sf.parse(endDate);//Unhandled exception type ParseException
//Date sDate = sf.parse(startDate);
Calendar c = Calendar.getInstance();
c.setTime(sDate);
long ls = c.getTimeInMillis();
c.setTime(eDate);
long le = c.getTimeInMillis();
getCnt=(int) ((le-ls)/(24*3600*1000));
return getCnt;
}
------解决方案--------------------sDate = sf.parse(startDate);//Unhandled exception type ParseException
eDate=sf.parse(endDate);//Unhandled exception type ParseException
上面两句应该这样写
sDate = new Date(sf.parse(startDate).getTime());
eDate = new Date(sf.parse(endDate).getTime());
------解决方案--------------------给你稍微改了一下:
public static int Get_Date_Count(String startDate, String endDate, int flag){
SimpleDateFormat sf = new SimpleDateFormat( "yyyyMMdd ");
try{
long ls = sf.parse(startDate).getTime();
long le = sf.parse(endDate).getTime();
return (int) ((le - ls) / (24 * 3600 * 1000));
}catch(Exception e){
e.printStackTrace();
}
return -1;
}
测试结果:
System.out.println (Get_Date_Count( "20070401 ", "20070403 ",1));
输出2!不知道是不是你要的结果?