最近用到了时间的查询,有一阵子没用时间在数据库和java上操作了。就发两个例子时间上的加减记录下。(问题最后还是靠数据库上的date_format('字符串时间','%Y-%m-%d %T')这样解决java传到数据库的String类型时间)

两个时间相差的月份(支持字符串的时间)

 
  
  1. public long getDistinceMonth(String beforedate, String afterdate) throws ParseException { 
  2.           SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd"); 
  3.           long monthCount=0
  4.          try
  5.              java.util.Date d1 = d.parse(beforedate); 
  6.              java.util.Date d2 = d.parse(afterdate); 
  7.               
  8.              monthCount = (d2.getYear() - d1.getYear()) * 12 + d2.getMonth() - d1.getMonth(); 
  9.  
  10.          }catch(ParseException e){ 
  11.              System.out.println("Date parse error!"); 
  12.          } 
  13.          return monthCount; 
  14.       } 

两个时间相差多少天

 
  
  1. public long getDistinceDay(String beforedate, String afterdate) throws ParseException { 
  2.           SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd"); 
  3.           long dayCount=0
  4.          try
  5.              java.util.Date d1 = d.parse(beforedate); 
  6.              java.util.Date d2 = d.parse(afterdate); 
  7.  
  8.              dayCount = (d2.getTime()-d1.getTime())/(24*60*60*1000); 
  9.  
  10.          }catch(ParseException e){ 
  11.              System.out.println("Date parse error!"); 
  12.          } 
  13.          return dayCount; 
  14.       } 

有不正确的地方希望大家指点指点,共同学习。