第一种:
public class Time {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date_start = null;
Date date_end = null;
try {
date_start = sdf.parse("2013-10-24");
date_end = sdf.parse("2013-11-20");
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(getGapCount(date_start,date_end));
}
/**
* 获取两个日期之间的间隔天数
* @return
*/
public static int getGapCount(Date startDate, Date endDate) {
Calendar fromCalendar = Calendar.getInstance();
fromCalendar.setTime(startDate);
fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
fromCalendar.set(Calendar.MINUTE, 0);
fromCalendar.set(Calendar.SECOND, 0);
fromCalendar.set(Calendar.MILLISECOND, 0);
Calendar toCalendar = Calendar.getInstance();
toCalendar.setTime(endDate);
toCalendar.set(Calendar.HOUR_OF_DAY, 0);
toCalendar.set(Calendar.MINUTE, 0);
toCalendar.set(Calendar.SECOND, 0);
toCalendar.set(Calendar.MILLISECOND, 0);
return (int) ((toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24));
}
}
第二种:
public class Demo {
public static void main(String[] args) throws ParseException {
String s1="2016-1-2";
String s2="2016-1-1";
DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar=new GregorianCalendar();
Date d1=df.parse(s1);
Date d2=df.parse(s2);
System.out.println((d1.getTime()-d2.getTime())/(60*60*1000*24));
}
}