当前位置: 代码迷 >> Java Web开发 >> 计算年的有关问题
  详细解决方案

计算年的有关问题

热度:84   发布时间:2016-04-17 01:14:03.0
计算年的问题
用java如何实现 两个时间段是几年的问题呢?比如:a=“20070101” b=“20090220”求a和b之间是几年?是大于2年?还是小于2年?还是等于2年?请高手做个指点谢谢

------解决方案--------------------
up,实用性问题,等高手解答
------解决方案--------------------
这样可以不?
new Date(b.getTime()-a.getTime()-86400000)-70
------解决方案--------------------
更改:
Java code
new Date(b.getTime()-a.getTime()-86400000).getYear()-70
------解决方案--------------------
Java code
public boolean compDate(String s1,String s2){        int day=0;         SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");        GregorianCalendar calendar1=new GregorianCalendar();        GregorianCalendar calendar2=new GregorianCalendar();        String s1="2006-04-21";        String s2="2006-04-25";        Date xxx1=new Date();        Date xxx2=new Date();        try {            xxx1=sf.parse(s1);            xxx2=sf.parse(s2);            day = (int) ((xxx2.getTime() - xxx1.getTime()) / 3600 / 24 / 1000);        } catch (ParseException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        if(day>10){            return true;        }else{            return false;        }        }
------解决方案--------------------
public static float CompareDate(String s1,String s2){
float year=0; 
SimpleDateFormat sf=new SimpleDateFormat("yyyyMMdd");

Date date1=new Date();
Date date1=new Date();
try {
date1=sf.parse(s1);
date2=sf.parse(s2);
year= (float) ((date2.getTime() - date1.getTime())) / 3600 / 24 / 1000/ 365;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return day;

}

在mian函数里用CompareDate("20070101","20090220")调用可以返回值:2.139726,所以是大于2年。
------解决方案--------------------
a=“20070101” b=“20090220”求a和b之间是几年 这个只精确到年的话有可能是个浮点型的 就楼上如是!
对于 只判断"是大于2年?还是小于2年?还是等于2年?"
你可以将字符串转成日期后,比较大小将小的直接给年数加2再转成日期类型和另外一个进行比较,就可判断 “是大于2年?还是小于2年?还是等于2年?” 这样就可以不考虑 闰年什么的
  相关解决方案