我想验证日期 (java.util.Date) 是否正确 比如 2021/02/31 不存在
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
dateFormat.setLenient(false);
try{
dateFormat.parse(dateFormat.format(date));
} catch(ParseException e) {
return false;
}
return true;
答案 0 :(得分:4)
我建议您使用现代日期时间 API*
使用 DateTimeFormatter#withResolverStyle(ResolverStyle.STRICT)
来严格解析日期。
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDate = "2021/02/31";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu/MM/dd", Locale.ENGLISH)
.withResolverStyle(ResolverStyle.STRICT);
try {
LocalDate date = LocalDate.parse(strDate, dtf);
// ...
} catch (DateTimeException e) {
System.out.println(e.getMessage());
}
}
}
输出:
Text '2021/02/31' could not be parsed: Invalid date 'FEBRUARY 31'
从 Trail: Date Time 了解有关现代日期时间 API 的更多信息。
另外,请注意 yyyy-mm-dd
不是您的日期字符串的正确格式,它具有 /
而不是 -
并且 m
用于一分钟,而不是一个月您必须使用 M
。
java.util
日期时间 API 及其格式化 API SimpleDateFormat
已过时且容易出错。建议完全停止使用它们并切换到 modern date-time API。出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7。如果您正在工作对于 Android 项目并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。
答案 1 :(得分:0)
首先,您的日期格式使用 mm
表示分钟,月份则需要为 MM
。
其次,我不确定您对 dateFormat.parse(dateFormat.format(date));
的意图。内部(dateFormat.format(Date)
)应该用于将日期转换为字符串,外部(dateFormat.parse(String)
)用于将字符串转换为日期。所以这似乎是一个毫无意义的操作。
我认为你的意思是这样的,它应该正确检查日期的有效性:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
try{
dateFormat.parse(dateFormat.format("2021-02-31"));
} catch(ParseException e) {
return false;
}
return true;
话虽如此,使用新的 Java 日期时间 API 始终是一种更好的方法,所以我会听从 @ArvindKumarAvinash 的回答,以获得更面向未来的解决方案。