Date now = new Date();
String format = "d";
//二零二一、五一
Date expo2021BeginDate = DateUtils.parseDate("2021-05-01 23:59:59", new String[]{"yyyy-MM-dd HH:mm:ss"});
//二零二二、十一
Date expo2021EndDate = DateUtils.parseDate("2022-10-01 23:59:59", new String[]{"yyyy-MM-dd HH:mm:ss"});
//开始时间-当前时间=距离开始时间,单位(天,"d")
System.out.println(DurationFormatUtils.formatDuration(expo2021BeginDate.getTime() - now.getTime(), format));
//结束时间-开始时间=相差时间,单位(天,"d")
System.out.println(
DurationFormatUtils.formatDuration(expo2021EndDate.getTime() - expo2021BeginDate.getTime(), format));
String day1 = DurationFormatUtils.formatPeriod(now.getTime(), expo2021EndDate.getTime(), format);
String day2 = DurationFormatUtils.formatPeriod(expo2021BeginDate.getTime(), now.getTime(), format);
System.out.println(day1);
System.out.println(day2);
character | duration element |
---|---|
y | years |
M | months |
d | days |
H | hours |
m | minutes |
s | seconds |
S | milliseconds |
注意:formatDuration和formatPeriod两个不同的方法,
计算天数推荐使用formatDuration
计算月份或者年数使用formatPeriod
(使用formatPeriod计算天数的时候会有一种----以为卡死的“慢”)