java 计算日期相差年月日分别是多少,有个老哥的方法有问题,这个是在基础上改的

import lombok.Builder;
import lombok.Data;

import java.util.Calendar;
import java.util.Date;

@Data
@Builder
public class DayCompare {
private int year;
private int month;
private int day;

/**
* 计算2个日期之间相差的 相差多少年月日,有个老哥的方法有问题,这个是在基础上改的
* 比如:2011-02-02 到 2017-03-02 相差 6年,1个月,0天
* @param fromDate
* @param toDate
* @return
*/
public static DayCompare dayComparePrecise(Date fromDate, Date toDate){
Calendar c1=Calendar.getInstance();
Calendar c2=Calendar.getInstance();
c1.setTime(fromDate);
c2.setTime(toDate);

int fromYear = c1.get(Calendar.YEAR);
int toYear = c2.get(Calendar.YEAR);
int year = toYear - fromYear;

// Map<String,String> map=new HashMap<>();
int day=c2.get(Calendar.DAY_OF_MONTH)-c1.get(Calendar.DAY_OF_MONTH);
int month=c2.get(Calendar.MONTH)-c1.get(Calendar.MONTH);
if(month<0){
month=12-c1.get(Calendar.MONTH)+c2.get(Calendar.MONTH);
year=year-1;
}
if(day<0){
day=c1.getActualMaximum(Calendar.DAY_OF_MONTH)-c1.get(Calendar.DAY_OF_MONTH)+c2.get(Calendar.DAY_OF_MONTH);
month=month-1;
}

return DayCompare.builder().day(day).month(month).year(year).build();
}

}

posted @ 2020-01-13 16:43  0o飞行天下o0  阅读(421)  评论(0编辑  收藏  举报