Check if the date is within the specified range in Java.
You can use the java.time.LocalDate class in Java to determine if a date is within a range. Here is an example code:
import java.time.LocalDate;
public class DateRangeExample {
public static void main(String[] args) {
// 定义日期范围
LocalDate startDate = LocalDate.of(2021, 1, 1);
LocalDate endDate = LocalDate.of(2021, 12, 31);
// 要判断的日期
LocalDate dateToCheck = LocalDate.of(2021, 6, 1);
// 判断日期是否在范围内
boolean isWithinRange = isWithinRange(dateToCheck, startDate, endDate);
// 输出结果
if (isWithinRange) {
System.out.println("日期在范围内");
} else {
System.out.println("日期不在范围内");
}
}
public static boolean isWithinRange(LocalDate date, LocalDate startDate, LocalDate endDate) {
return date.isAfter(startDate) && date.isBefore(endDate) || date.isEqual(startDate) || date.isEqual(endDate);
}
}
In the example above, we defined a date range (from January 1, 2021 to December 31, 2021) and specified the date to be checked (June 1, 2021). We then used the isWithinRange method to determine if the date falls within the range. If the date is within the range, true is returned, otherwise false. Finally, we output the corresponding information based on the result.
Please make sure your Java version is 8 or higher before using the java.time.LocalDate class.