这篇文章距离最后更新已过896 天,如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!
首先
<dependencies>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
其次
import org.joda.time.Interval;
import org.joda.time.Period;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @Author youzi
* @ClassName TestDateUtil
* startDate 开始时间
* endDate 结束时间
* dateFormat 时间格式(形如 yyyy-MM-dd)
* @return 相差的月份数和天数 months 、 days
* @throws ParseException
* @Date 2022/6/22 14:02
* @Description 计算两个时间差
*/
public class TestDateUtil {
public static void main(String[] args) throws ParseException {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date dateStart = df.parse("2022-03-04");
Date dateEnd = df.parse("2022-06-03");
if (dateStart.getTime() > dateEnd.getTime()) {
Date temp = dateStart;
dateStart = dateEnd;
dateEnd = temp;
}
Calendar c = Calendar.getInstance();
c.setTime(dateEnd);
c.add(Calendar.DAY_OF_MONTH, 1);
//这是明天
dateEnd = c.getTime();
Interval interval = new Interval(dateStart.getTime(), dateEnd.getTime());
Period p = interval.toPeriod();
Integer years = p.getYears();
Integer months = p.getMonths();
Integer weeks = p.getWeeks();
Integer days = p.getDays();
Integer resultMonths = years * 12 + months;
Integer resultDays = weeks * 7 + days;
Map<String, Integer> result = new HashMap<>();
result.put("months", resultMonths);
result.put("days", resultDays);
System.out.println(result);
}
}