背景
需要计算两个日期直接的天数,这里使用Joda Time这个第三方库解决这个问题,因为不太想操心闰年之类的复杂情况。
解决
Maven
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.10</version>
</dependency>
Gradle
compile group: 'joda-time', name:'joda-time', version:'2.10.10'
Java
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Days;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date startDate = dateFormat.parse("2021-10-01 00:00:00");
Date expireDate = dateFormat.parse("2021-10-06 23:59:59");
// 计算天数
String timeZone = "Asia/Shanghai";
DateTimeZone CHINA = DateTimeZone.forID(timeZone);
DateTime start = new DateTime(startDate, CHINA);
DateTime end = new DateTime(expireDate.getTime(), CHINA);
Days dias = Days.daysBetween(start, end);
System.out.printf("间隔天数:%d", dias.getDays());
} catch (ParseException e) {
e.printStackTrace();
}
}
}
结果:
间隔天数:5