java.time
java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,改用modern Date-Time API*。
您在代码中观察到的问题是您在使用SimpleDateFormat 时遇到的奇怪问题之一。 SimpleDateFormat 不会因为格式错误而抛出异常,而是尝试错误地解析日期字符串。
使用现代日期时间 API java.time 的解决方案:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class Main {
public static void main(String[] args) {
String sFecha = "10/21/2021";
try {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse(sFecha, dtf);
System.out.println(date);
} catch (DateTimeParseException e) {
System.out.println("A problem occured while parsing the date string.");
// ...Handle the exception
}
}
}
输出:
A problem occured while parsing the date string.
现在,把格式改成MM/dd/yyyy,就可以看到日期字符串解析成功了。
从 Trail: Date Time 了解有关现代日期时间 API 的更多信息。
如果你想使用SimpleDateFormat:
将false 传递给SimpleDateFormat#setLenient,true 被默认设置。
演示:
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
String sFecha = "10/21/2021";
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(false);
System.out.println(sdf.format(sdf.parse(sFecha)));
} catch (java.text.ParseException e) {
System.out.println("A problem occured while parsing the date string.");
// ...Handle the exception
}
}
}
输出:
A problem occured while parsing the date string.
* 如果您正在为一个 Android 项目工作,并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring。请注意,Android 8.0 Oreo 已经提供了support for java.time。