你的位置:首页 > Java教程

[Java教程]【转】JAVA获取连个日期之间的差


public class Test2{

 public long getTwoDay(Date begin_date, Date end_date) {
  long day = 0;
  try {
   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
   String sdate = format.format(Calendar.getInstance().getTime());
   
   if (begin_date == null) {
    begin_date = format.parse(sdate);
   }
   if (end_date == null) {
    end_date = format.parse(sdate);
   }
   day = (end_date.getTime() - begin_date.getTime())
     / (24 * 60 * 60 * 1000);
  } catch (Exception e) {
   return -1;
  }
  return day;
 }

 public static void main(String[]args){
  Test2 t=new Test2();
    try {
     Date date1 = new SimpleDateFormat("yyyy-mm-dd").parse("2006-06-08");
     Date date2 = new SimpleDateFormat("yyyy-mm-dd").parse("2006-06-12");
        long day= t.getTwoDay(date1, date2);
        System.out.println(day);
  } catch (ParseException e) {
   e.printStackTrace();
  } 
 }
}