java calendar 日期差_java利用Calendar怎么计算两个日期只差?

package test;import java.util.Calendar;import java.util.Date;public class A1{private static void calc ( String from, String to ){String reg = "\\-";Calendar calendar = Calendar.getInstance ();String[] f = from.trim ().split (reg);String[] t = to.trim ().split (reg);calendar.set (Integer.parseInt (f[0]), Integer.parseInt (f[1]) - 1, Integer.parseInt (f[2]));long fd1 = calendar.getTime ().getTime ();calendar.set (Integer.parseInt (t[0]), Integer.parseInt (t[1]) - 1, Integer.parseInt (t[2]));long td1 = calendar.getTime ().getTime ();String date1 = fd1 < td1 ? from : to;String date2 = td1 > fd1 ? to : from;f = date1.trim ().split (reg);t = date2.trim ().split (reg);String d3temp = Integer.parseInt (t[1]) - 1 < 10 ? "0" + (Integer.parseInt (t[1]) - 1) : Integer.parseInt (t[1]) - 1 + "";String d3temp1 = Integer.parseInt (f[2]) - 1 < 10 ? "0" + (Integer.parseInt (f[2]) - 1) : Integer.parseInt (f[2]) - 1 +"";String date3 = t[0] + "-" + d3temp + "-" + d3temp1;String d4temp = Integer.parseInt (t[1]) - 1 < 10 ? "0" +(Integer.parseInt (t[1]) - 1) :Integer.parseInt (t[1]) - 1 + "";String d4temp1 = f[2].length () == 1 ? "0" + f[2] : f[2];String date4 = t[0] + "-" + d4temp + "-" + d4temp1;calendar.set (Integer.parseInt (f[0]), Integer.parseInt (f[1]) - 1, Integer.parseInt (f[2]));Date d1 = calendar.getTime ();calendar.set (Integer.parseInt (t[0]), Integer.parseInt (t[1]) - 2, Integer.parseInt (f[2]) - 1);Date d3 = calendar.getTime ();calendar.set (Integer.parseInt (t[0]), Integer.parseInt (t[1]) - 2, Integer.parseInt (f[2]));Date d4 = calendar.getTime ();calendar.set (Integer.parseInt (t[0]), Integer.parseInt (t[1]) - 1, Integer.parseInt (t[2]));Date d2 = calendar.getTime ();long desc1 = d3.getTime () - d1.getTime ();long year1 = desc1 / 1000 / 60 / 60 / 24 / 365;long month1 = desc1 / 1000 / 60 / 60 / 24 / 30 % 12;long desc2 = d2.getTime () - d4.getTime ();long day = desc2 / 1000 / 60 / 60 / 24 % 30;String yearstr = year1 == 0 ? "" : year1 + " 年 ";System.out.println (date1 + " 到 " + date3 + " 为 " + yearstr + month1 + " 个月," + date4 + " 到 " + date2 + " 总共有 " + day + " 天,得到 " + year1 + " 年 " + month1 + " 个月 " + day + " 天.");}public static void main ( String[] args ){calc ("2014-07-20", "2014-11-10");calc ("2014-07-20", "2015-05-10");calc ("2014-07-20", "2016-05-10");}}

取消

评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值