在Java中处理公历(格里高利历)日历验证时,主要涉及java.util.Calendar
、java.util.GregorianCalendar
和java.time
包(Java 8+)中的类。公历日历验证通常包括日期有效性检查、闰年判断、日期范围验证等。
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class DateValidator {
public static boolean isValidDate(String dateStr, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(false); // 关键设置,严格验证
try {
sdf.parse(dateStr);
return true;
} catch (ParseException e) {
return false;
}
}
// 使用示例
public static void main(String[] args) {
System.out.println(isValidDate("2023-02-29", "yyyy-MM-dd")); // false (2023不是闰年)
System.out.println(isValidDate("2024-02-29", "yyyy-MM-dd")); // true (2024是闰年)
}
}
public class LeapYearChecker {
public static boolean isLeapYear(int year) {
// 格里高利历闰年规则:
// 1. 能被4整除但不能被100整除,或
// 2. 能被400整除
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class Java8DateValidator {
public static boolean isValidDate(String dateStr, String pattern) {
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
LocalDate.parse(dateStr, formatter);
return true;
} catch (DateTimeParseException e) {
return false;
}
}
}
import java.time.LocalDate;
public class DateRangeValidator {
public static boolean isWithinRange(LocalDate testDate, LocalDate startDate, LocalDate endDate) {
return !(testDate.isBefore(startDate) || testDate.isAfter(endDate));
}
}
setLenient(false)
或使用了不严格的解析器。java.time
包中的类,它们是不可变的且线程安全。SimpleDateFormat
时一定要设置setLenient(false)
。没有搜到相关的文章