java计算工龄
计算工龄原则:若是2000-10-12作为开始工作时间,则到下一年的2001-10-13算为一年。有个bug,不满一年的工龄是错误的。
import java.util.Date; import java.util.Calendar; public int workAge(Date nowTime, Date workTime){ int year = 0; //当前时间的年月日 Calendar cal = Calendar.getInstance(); cal.setTime(nowTime); int nowYear = cal.get(Calendar.YEAR); int nowMonth = cal.get(Calendar.MONTH); int nowDay = cal.get(Calendar.DAY_OF_MONTH); //开始工作时间的年月日 cal.setTime(workTime); int workYear = cal.get(Calendar.YEAR); int workMonth = cal.get(Calendar.MONTH); int workDay = cal.get(Calendar.DAY_OF_MONTH); //得到工龄 year = nowYear - workYear; //得到年差 //若目前月数少于开始工作时间的月数,年差-1 if (nowMonth < workMonth){ year = year - 1; }else if (nowMonth == workMonth){ //当月数相等时,判断日数,若当月的日数小于开始工作时间的日数,年差-1 if (nowDay < workDay){ year = year - 1; } } return year; }
/** * 计算工龄 * @param begin "yyyy-MM-dd" * @return double * @throws ParseException */ public static double workYears(String begin) { Calendar dayEnd = Calendar.getInstance(); Calendar dayBegin = Calendar.getInstance(); try { dayBegin.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(begin)); } catch (ParseException e) { e.printStackTrace(); } //初始计算 double result= dayEnd.get(Calendar.MONTH) +dayEnd.get(Calendar.YEAR)*12 -dayBegin.get(Calendar.MONTH) - dayBegin.get(Calendar.YEAR)*12; //BigDecimal.ROUND_HALF_UP表示四舍五入,BigDecimal.ROUND_HALF_DOWN也是五舍六入,BigDecimal.ROUND_UP表示进位处理(就是直接加1),BigDecimal.ROUND_DOWN表示直接去掉尾数。 return new BigDecimal(result/12).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); }