bean产出类
package com.springboot.redisdemo.bean;
import lombok.Builder;
import lombok.Data;
/**
* 时间比较结果产出
*/
@Data
@Builder
public class DayCompareBean {
private int year;
private int month;
private int day;
}
计算方法
/**
* 计算两个日期相差的 天数、月数、年数
* @param fromDate
* @param toDate
* @return
*/
private static DayCompareBean 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 DayCompareBean.builder().day(day).month(month).year(year).build();
}
我的业务是如果天数不到1 也算1天。可以写个三元判断一下就好了。