当前位置: 代码迷 >> Android >> Android 获取二个日期相差天数
  详细解决方案

Android 获取二个日期相差天数

热度:72   发布时间:2016-04-28 07:40:05.0
Android 获取2个日期相差天数
    最近一直需要用到日期处理。
     返回2个日期的相差天数。
   
/**
* 获取两个日期之间的间隔天数
* @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));
}




//测试
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   Date date_start = null;
   Date date_end = null;
try {
date_start = sdf.parse("2013-10-16");
date_end = sdf.parse("2013-10-19");
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
  System.out.println(getGapCount(date_start,date_end));
  相关解决方案