Java 计算2个时间相差多少年,多少个月,多少天的几种方式
一、Java 时间比较需求
1.A时间到B时间,相差多少年,月,日。
如:2011-02-02 到 2017-03-02 ,结果为:
- 相差 6年,1个月,0天
2.A时间到B时间, 相差年,月,日各是多少。
如:2011-02-02 到 2017-03-02,结果为:
-
以年为单位相差为:6年
-
以月为单位相差为:73个月
-
以日为单位相差为:2220天
3.A时间到B时间,相差多少年
如:2011-02-02 到 2017-03-02,结果大约为:
- 6.1年
这个需求体现在如我加入公司 3 年 6 个月,也可以说是3.5年。
二、Java 时间代码实现
日期比较对象 DayCompare代码用到了 lombok 回头会讲到。如果你不用,其实就是把getter / setter方法自己写一遍,还有构造方法。
@Data
@Builder
public static class DayCompare{
private int year;
private int month;
private int day;
}
2.1 A时间到B时间,相差多少年,月,日。
/**
* 计算2个日期之间相差的 相差多少年月日
* 比如:2011-02-02 到 2017-03-02 相差 6年,1个月,0天
* @param fromDate
* @param toDate
* @return
*/
public static DayCompare dayComparePrecise(Date fromDate,Date toDate){
Calendar from = Calendar.getInstance();
from.setTime(fromDate);
Calendar to = Calendar.getInstance();
to.setTime(toDate);
int fromYear = from.get(Calendar.YEAR);
int fromMonth = from.get(Calendar.MONTH);
int fromDay = from.get(Calendar.DAY_OF_MONTH);
int toYear = to.get(Calendar.YEAR);
int toMonth = to.get(Calendar.MONTH);
int toDay = to.get(Calendar.DAY_OF_MONTH);
int year = toYear - fromYear;
int month = toMonth - fromMonth;
int day = toDay - fromDay;
return DayCompare.builder().day(day).month(month).year(year).build();
}
2.2 A时间到B时间, 相差年,月,日各是多少
/**
* 计算2个日期之间相差的 以年、月、日为单位,各自计算结果是多少
* 比如:2011-02-02 到 2017-03-02
* 以年为单位相差为:6年
* 以月为单位相差为:73个月
* 以日为单位相差为:2220天
* @param fromDate
* @param toDate
* @return
*/
public static DayCompare dayCompare(Date fromDate,Date toDate){
Calendar from = Calendar.getInstance();
from.setTime(fromDate);
Calendar to = Calendar.getInstance();
to.setTime(toDate);
//只要年月
int fromYear = from.get(Calendar.YEAR);
int fromMonth = from.get(Calendar.MONTH);
int toYear = to.get(Calendar.YEAR);
int toMonth = to.get(Calendar.MONTH);
int year = toYear - fromYear;
int month = toYear * 12 + toMonth - (fromYear * 12 + fromMonth);
int day = (int) ((to.getTimeInMillis() - from.getTimeInMillis()) / (24 * 3600 * 1000));
return DayCompare.builder().day(day).month(month).year(year).build();
}
2.3 A时间到B时间,相差多少年
/**
* 计算2个日期相差多少年
* 列:2011-02-02 ~ 2017-03-02 大约相差 6.1 年
* @param fromDate
* @param toDate
* @return
*/
public static String yearCompare(Date fromDate,Date toDate){
DayCompare result = dayComparePrecise(fromDate, toDate);
double month = result.getMonth();
double year = result.getYear();
//返回2位小数,并且四舍五入
DecimalFormat df = new DecimalFormat("######0.0");
return df.format(year + month / 12);
}