java计算2个时间相差多少年,多少个月,多少天

 

  1. import  java.util.Calendar; 
  2. public  class  Y  { 
  3.    public  static  void  main(String[]  args)  { 
  4.       int  ret[]  =  getDateLength( "20050531 ", "20070101 "); 
  5.       System.out.println(ret[0]  +  ": "  +  ret[1]  +  ": "  +  ret[2]); 
  6.    } 
  7.    static  int[]  getDateLength(String  fromDate, String  toDate)  { 
  8.       Calendar  c1  =  getCal(fromDate); 
  9.       Calendar  c2  =  getCal(toDate); 
  10.       int[]  p1  =  {  c1.get(Calendar.YEAR), c1.get(Calendar.MONTH), c1.get(Calendar.DAY_OF_MONTH)  }; 
  11.       int[]  p2  =  {  c2.get(Calendar.YEAR), c2.get(Calendar.MONTH), c2.get(Calendar.DAY_OF_MONTH)  }; 
  12.       return  new  int[]  {  p2[0]  -  p1[0], p2[0]  *  12  +  p2[1]  -  p1[0]  *  12  -  p1[1], (int)  ((c2.getTimeInMillis()  -  c1.getTimeInMillis())  /  (24  *  3600  *  1000))  }; 
  13.    } 
  14.    static  Calendar  getCal(String  date)  { 
  15.       Calendar  cal  =  Calendar.getInstance(); 
  16.       cal.clear(); 
  17.       cal.set(Integer.parseInt(date.substring(04)), Integer.parseInt(date.substring(46))  -  1, Integer.parseInt(date.substring(68))); 
  18.       return  cal; 
  19.    } 

计算年的差值和天的差值比较简单。
关键是月的差值,可以用等价的概念把年退到月,比如2007年1月,等价于2006年13月,同理等价于0年(2007*12+1)月。
这样y1年m1月到y2年m2月  分别等价于0年(y1*12+m1)月和0年(y2*12-m2)月
月份之差就是:y2*12+m2-y1*12-m1

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值