java.time
java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,改用modern Date-Time API*。
使用现代日期时间 API java.time 的解决方案:
让我们首先尝试按照您的方式进行操作:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String[] arr = { "2015-02-02", "2015-02-02 23:23:23" };
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ENGLISH);
for (String s : arr) {
System.out.println("Attempting to parse '" + s + "':");
LocalDate date = LocalDate.parse(s, dtf);
System.out.println("Parsed successfully: " + date);
}
}
}
输出:
尝试解析“2015-02-02”:
解析成功:2015-02-02
尝试解析“2015-02-02 23:23:23”:
线程“main”中的异常 java.time.format.DateTimeParseException: Text
'2015-02-02 23:23:23' 无法解析,在索引 10 处找到未解析的文本
如您所见,java.time API 正确地引发了异常,通知您该问题。另一方面,SimpleDateFormat 会静默解析输入字符串,这会导致您发布的问题。
因此,使用现代日期时间 API,您有两个简单的选择:
- 只需捕获异常并说第二个输入(即
2015-02-02 23:23:23)不是指定日期模式的日期字符串。
- 使用函数
DateTimeFormatter#parse(CharSequence, ParsePosition) 并将ParsePosition 索引设置为0。
下面是第二个选项的演示:
import java.text.ParsePosition;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String[] arr = { "2015-02-02", "2015-02-02 23:23:23" };
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ENGLISH);
for (String s : arr) {
ParsePosition pp = new ParsePosition(0);
LocalDate.from(dtf.parse(s, pp));
if (pp.getIndex() < s.length()) {
System.out.println("'" + s + "' is not a date string as per the specified date pattern.");
}
}
}
}
输出:
'2015-02-02 23:23:23' 不是指定日期模式的日期字符串。
ONLINE DEMO
注意:Never use SimpleDateFormat or DateTimeFormatter without a Locale.
从 Trail: 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。