java日期间相隔年月日计算
Posted Brin Page
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java日期间相隔年月日计算相关的知识,希望对你有一定的参考价值。
/**
* 获取date1相距date2多少天, date2>date1
* @param date1
* @param date2
* @return
* @throws ParseException
*/
public static int getDaysSpace(String date1,String date2){
Calendar cal = Calendar.getInstance();
cal.setTime(getDate(date1, "yyyyMMdd"));
long time1 = cal.getTimeInMillis();
cal.setTime(getDate(date2, "yyyyMMdd"));
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
return Integer.parseInt(String.valueOf(between_days));
}
/**
* 获取date1相距date2几个月, date2>date1
* @param date1
* @param date2
* @return
* @throws ParseException
*/
public static float getMonthSpace(String date1, String date2){
float result = 0;
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(getDate(date1, "yyyyMMdd"));
c2.setTime(getDate(date2, "yyyyMMdd"));
if(c2.get(Calendar.DATE) - c1.get(Calendar.DATE) >= 0){
result = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) * 12.0f + (c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH)) + (c2.get(Calendar.DATE) - c1.get(Calendar.DATE))/30.0f;
}else{
result = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) * 12.0f + (c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH)) - 1.0f + (c2.get(Calendar.DATE) - c1.get(Calendar.DATE))/30.0f;
}
DecimalFormat df = new DecimalFormat("0.00");
return Float.parseFloat(df.format(result));
}
/**
* 获取date1相距date2几年, date2>date1
* @param date1
* @param date2
* @return
* @throws ParseException
*/
public static float getYearSpace(String date1, String date2) {
DecimalFormat df = new DecimalFormat("0.00");
return Float.parseFloat(df.format(getMonthSpace(date1, date2)/12.0f));
}
以上是关于java日期间相隔年月日计算的主要内容,如果未能解决你的问题,请参考以下文章