import java.text.ParseException;
public class Hello {
public static void main(String[] args) throws ParseException {
System.out.println(new java.text.SimpleDateFormat("yyyy-MM-dd").parse("23-06-2015"));
}
}
为什么这会返回Sun Dec 05 00:00:00 GMT 28
我期待着一个例外。为什么SimpleDateFormat不会为无效格式引发异常?
您无法从格式化状态的字符串日期获取日期对象。因此,当你试图格式化日期时,无论你的格式如何,JVM都给你一个通用的日期。 – Anant666
尝试它:'java.time.format.DateTimeFormatter.ofPattern(“yyyy-MM-dd”)。parse(“23-06-2015”);',如果您使用的是Java8。 – sndyuk
因为'SimpleDateFormat'是这样设计的。事实证明这是一个糟糕的设计决定。如果您在解析之前在'SimpleDateFormat'上调用'setLenient(false)',您可能会得到预期的异常。但是最好的解决方案是@sndyuk建议的方法:完全跳过'SimpleDateFormat'并使用'DateTimeFormatter'。如果你还没有使用Java 8,你可以在[ThreeTen Backport](http://www.threeten.org/threetenbp/)中找到它。 –