一、日期范围判断
说明:包含两个端点值,即日期范围的闭区间。
举例:判断日期【2021-03-22】是否在日期范围【2021-03-22,2021-03-30】闭区间内
public static boolean validDate(String paramDateStr, String dateRange) {
String[] dateRangeArr = dateRange.split(",");
LocalDate paramDate = null, startDate = null, endDate = null;
try {
paramDate = LocalDate.parse(paramDateStr);
startDate = LocalDate.parse(dateRangeArr[0]);
endDate = LocalDate.parse(dateRangeArr[1]);
} catch (DateTimeParseException e) {
System.out.println("日期格式化异常");
return false;
}
// 不在日期范围闭区间内
return paramDate.compareTo(startDate) >= 0 && paramDate.compareTo(endDate) <= 0;
}
public static void main(String[] args) {
String paramDateStr = "2021-03-22";
String dateRange = "2021-03-22,2021-03-30";
System.out.println(validDate(paramDateStr, dateRange));
}
运行输出:true
二、时间段判断
说明:包含每个时间段的端点值,即每个时间段范围的闭区间。
举例:判断时间点【11:35】是否在时间段【11:30-12:00,14:20-16:40,18:10-20:25】内
public static boolean validTime(String paramTimeStr, String timeRange) {
LocalTime paramTime = null;
try {
paramTime = LocalTime.parse(paramTimeStr);
} catch (IllegalArgumentException e) {
System.out.println("时间格式化异常");
return false;
}
String[] timeRangeArr = timeRange.split(",");
for (String rTime : timeRangeArr) {
LocalTime startTime = null, endTime = null;
String[] rTimeArr = rTime.split("-");
try {
startTime = LocalTime.parse(rTimeArr[0]);
endTime = LocalTime.parse(rTimeArr[1]);
} catch (IllegalArgumentException e) {
System.out.println("时间格式化异常");
return false;
}
if (paramTime.compareTo(startTime) > -1 && paramTime.compareTo(endTime) < 1) {
// 有一个时间段符合,则通过
return true;
}
}
// 不在任何时间段内
return false;
}
public static void main(String[] args) {
String paramTimeStr = "11:35";
String timeRange = "11:30-12:00,14:20-16:40,18:10-20:25";
System.out.println(validTime(paramTimeStr, timeRange));
}
运行输出:true
三、是否为工作日
public static boolean isWorkday(String paramDateStr) {
LocalDate paramDate = null;
try {
paramDate = LocalDate.parse(paramDateStr);
} catch (DateTimeParseException e) {
System.out.println("日期格式化异常");
return false;
}
int week = paramDate.getDayOfWeek().getValue();
return week <= 5;
}
public static void main(String[] args) {
String paramDateStr = "2021-03-21";
System.out.println(isWorkday(paramDateStr));
}
运行输出:false