一、时间格式化
public static String DateFormat(Date date) {
return DateFormat(date, "yyyy-MM-dd HH:mm:ss");
}
public static String DateFormat(Date date, String format) {
return new SimpleDateFormat(format).format(date);
}
二、时间计算(时间加减)
public static Date Calculation(int unit, int i) {
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(unit, i);
return cal.getTime();
}
三、两个时间之间的差值
public static String TimeLeft(Date date, String yearUnit) {
Period between = TimeLeft(date);
if (between.getYears() != 0) {
return Math.abs(between.getYears()) + yearUnit;
} else if (between.getMonths() != 0) {
return Math.abs(between.getMonths()) + "月";
} else if (between.getDays() != 0) {
return Math.abs(between.getDays()) + "天";
} else {
return "0天";
}
}
public static Period TimeLeft(Date date) {
LocalDate ageDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Period between = Period.between(ageDate, LocalDate.now());
log.info("相差: {} 年 {} 月 {} 日", Math.abs(between.getYears()), Math.abs(between.getMonths()), Math.abs(between.getDays()));
return between;
}