java日期间相隔年月日计算

Myth丶恋晨 2021-11-11 13:34 466阅读 0赞

/**
* 获取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));
}

转载于:https://www.cnblogs.com/Jiphen/p/6180354.html

发表评论

表情:
评论列表 (有 0 条评论,466人围观)

还没有评论,来说两句吧...

相关阅读

    相关 获取年月

    前言 需求:获取当前日期的前一个月份 当月有 31 天时,JS 日期对象 setMonth 问题 1. 一般做法 当前日期如果不是 31 号, 是没问题的,是