计算员工在职时长

在只需要年份的情况下:

//参数:起止时间

public int getCareerage(Date startDate, Date endDate) {

Calendar calStart = Calendar.getInstance();

calStart.setTime(DateUtil.getBeginOfDay(startDate));    //获取一天的开始 (00:00:00)

Calendar calEnd = Calendar.getInstance();

calEnd.setTime(DateUtil.getBeginOfDay(endDate));

int Year = 0;

calStart.add(Calendar.YEAR, 1);

while (calStart.getTimeInMillis() <= calEnd.getTimeInMillis()) {

Year++;

calStart.add(Calendar.YEAR, 1);

if (Year > 10000) {

break;

}

return Year;

}

在需要xx年xx天的情况下

public String getCareerage(Date startDate, Date endDate) {

Calendar calStart = Calendar.getInstance();

calStart.setTime(DateUtil.getBeginOfDay(startDate));

Calendar calEnd = Calendar.getInstance();

calEnd.setTime(DateUtil.getBeginOfDay(endDate));

int Year = 0;

calStart.add(Calendar.YEAR, 1);

while (calStart.getTimeInMillis() <= calEnd.getTimeInMillis()) {

Year++;

calStart.add(Calendar.YEAR, 1);

if (Year > 10000) {

break;

}

}

calStart.setTime(DateUtil.getBeginOfDay(startDate));

calStart.add(Calendar.YEAR, Year);

calStart.add(Calendar.DATE, -1);

Long day = (calEnd.getTime().getTime() - calStart.getTime().getTime()) / (1000 * 3600 * 24);

System.out.println("year:"+Year +"----"+"day:"+day);

if(Year!=0 && day!=0){

return Year + "年" + day + "天";

}

else if(Year==0 && day!=0){

return day + "天";

}else if(Year!=0 && day==0){

return Year+"周年";

}else if(Year==0 && day ==0){

return "0天";

}

return null;

}


DateUtil.getBeginOfDay  方法

public static Date getBeginOfDay(Date date) {

Calendar cal = Calendar.getInstance();

try {

cal.setTime(date);

cal.set(Calendar.HOUR_OF_DAY, 0);

cal.set(Calendar.MINUTE, 0);

cal.set(Calendar.SECOND, 0);

cal.set(Calendar.MILLISECOND, 0);

return cal.getTime();

} catch (Exception e) {

return null;

}

}


你可能感兴趣的:(模块,算法)