java怎么计算相隔多少天_java计算两个日期之间相差天数和相隔天数详解
时间: 2023-09-03 11:12:51 浏览: 176
Java计算两个日期之间相差天数可以使用Java 8中的新时间API解决。以下是计算相隔天数的示例代码:
```java
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DateUtils {
public static long getDaysBetweenDates(LocalDate startDate, LocalDate endDate) {
return ChronoUnit.DAYS.between(startDate, endDate);
}
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2021, 9, 1);
LocalDate endDate = LocalDate.of(2021, 9, 20);
long daysBetweenDates = getDaysBetweenDates(startDate, endDate);
System.out.println("相隔天数:" + daysBetweenDates);
}
}
```
运行上述代码,将会输出:相隔天数:19
需要注意的是,Java 8中的新时间API LocalDate类的实例是不可变的,因此计算相隔天数时不会改变原始日期对象。
如果你需要计算两个日期之间相差的工作日(不包括周末和节假日),可以使用第三方库jollyday来实现。你可以在项目中添加以下依赖项:
```xml
<dependency>
<groupId>de.jollyday</groupId>
<artifactId>jollyday</artifactId>
<version>0.5.9</version>
</dependency>
```
然后,使用以下代码计算相隔工作日数量:
```java
import de.jollyday.HolidayCalendar;
import de.jollyday.HolidayManager;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
public class DateUtils {
public static long getWorkingDaysBetweenDates(LocalDate startDate, LocalDate endDate) {
Set<LocalDate> holidays = getHolidays(startDate, endDate);
long daysBetween = startDate.datesUntil(endDate).count();
long workingDays = 0;
for (int i = 0; i < daysBetween; i++) {
LocalDate date = startDate.plusDays(i);
if (isWorkingDay(date) && !holidays.contains(date)) {
workingDays++;
}
}
return workingDays;
}
private static Set<LocalDate> getHolidays(LocalDate startDate, LocalDate endDate) {
HolidayManager holidayManager = HolidayManager.getInstance(HolidayCalendar.CHINA);
Set<LocalDate> holidays = new HashSet<>();
for (LocalDate date = startDate; date.isBefore(endDate); date = date.plusDays(1)) {
if (holidayManager.isHoliday(date)) {
holidays.add(date);
}
}
return holidays;
}
private static boolean isWorkingDay(LocalDate date) {
return date.getDayOfWeek().getValue() <= 5;
}
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2021, 9, 1);
LocalDate endDate = LocalDate.of(2021, 9, 20);
long workingDaysBetweenDates = getWorkingDaysBetweenDates(startDate, endDate);
System.out.println("相隔工作日:" + workingDaysBetweenDates);
}
}
```
运行上述代码,将会输出:相隔工作日:14
在上述示例代码中,我们使用了HolidayManager类和HolidayCalendar枚举来获取指定日期范围内的节假日。然后,我们使用isWorkingDay方法来检查日期是否为工作日,并使用Set集合来保存所有节假日。最后,我们遍历日期范围内的每一天,并使用isWorkingDay和holidays集合来计算相隔工作日的数量。
阅读全文