java 计算2日期之差

 

 

private static int calDiffDays(String str1, String str2) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(sdf.parse(str1));
		Calendar cal2 = Calendar.getInstance();
		cal2.setTime(sdf.parse(str2));
		long l = cal2.getTimeInMillis() - cal1.getTimeInMillis();
		int days = new Long(l / (1000 * 60 * 60 * 24)).intValue();
		System.out.println("2个日期之间相差:" + days + "天。");
		return days;
	}

 

 

用calendar.getTimeInMillis比date.getTime准确,更建议用前者。

refurl:http://zhidao.baidu.com/question/585243394.html

 

 

 

 

你可能感兴趣的:(java)