java日期工具类
public class DateUtil {
public static <T extends BaseEntity> void setCreateDate(T t ) {
t.setCreateDate(new Date());
}
public static <T extends BaseEntity> void setUpdateDate(T t ) {
t.setUpdateDate(new Date());
}
public static Date getDate() {
return new Date();
}
/**
* 判断年份是不是 闰年
* @param year
* @return
*/
public static boolean isLeapYear(int year){
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
/**
* 将时间转化为 yyyyMMdd 的数值
* @param d 需要转换的时间
* @return yyyyMMdd 数组
*/
public static int getDayNum(Date d){
Calendar cal = Calendar.getInstance();
cal.setTime(d);
int yearNum = cal.get(Calendar.YEAR);
// ps 月份从0开始
int monthNum = cal.get(Calendar.MONTH)+1;
int dayNum = cal.get(Calendar.DAY_OF_MONTH);
return yearNum*10000 + monthNum * 100 + dayNum;
}
/**
* 计算2个日期之间相差的 以年、月、日为单位,各自计算结果是多少
* 比如:2011-02-02 到 2017-03-02
* 以年为单位相差为:6年
* 以月为单位相差为:73个月
* 以日为单位相差为:2220天
* @param fromDate
* @param toDate
* @return
*/
public static Integer dayCompare(String fromDate,String toDate) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
Date fDate = simpleDateFormat.parse(fromDate);
Date tDate = simpleDateFormat.parse(toDate);
Calendar from = Calendar.getInstance();
from.setTime(fDate);
Calendar to = Calendar.getInstance();
to.setTime(tDate);
int day = (int) ((to.getTimeInMillis() - from.getTimeInMillis()) / (24 * 3600 * 1000));
return day;
}
public static void main(String[] args) {
// Calendar cal = Calendar.getInstance();
// System.out.println(getDayNum(cal.getTime()));
// try {
// System.out.println(dayCompare("2020-01-01", "2020-12-31"));
// } catch (ParseException e) {
// e.printStackTrace();
// }
}
}