为什么 SimpleDateFormat 不会因格式无效而抛出异常?
Why SimpleDateFormat does not throw exception for invalid format?
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"));
}
}
为什么这个 returns Sun Dec 05 00:00:00 GMT 28
我期待一个例外。
JavaSimpleDateFormat
的文档对重复的模式字母有这样的说法:
Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields
(强调我的)
所以对于解析,"yyyy-MM-dd"
等价于"y-M-d"
.
使用此模式,"23-06-2015"
被解析为 year = 23, month = 6, dayOfMonth = 2015
。
默认情况下,此问题从 0023 年 6 月 1 日开始解决,并向前计算 2015 天,将您带到 0028 年 12 月 5 日。
您可以使用 SimpleDateFormat.setLenient(false)
更改此行为 - 禁用宽大处理,它将为超出范围的数字抛出异常。 Calendar.setLenient()
中对此进行了正确记录
请注意,对于 Java 8 中的新代码,最好避免使用旧的 Date
和 Calendar
类。如果可以,请使用 LocalDateTime.parse(CharSequence text, DateTimeFormatter formatter)
。
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"));
}
}
为什么这个 returns Sun Dec 05 00:00:00 GMT 28
我期待一个例外。
JavaSimpleDateFormat
的文档对重复的模式字母有这样的说法:
Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields
(强调我的)
所以对于解析,"yyyy-MM-dd"
等价于"y-M-d"
.
使用此模式,"23-06-2015"
被解析为 year = 23, month = 6, dayOfMonth = 2015
。
默认情况下,此问题从 0023 年 6 月 1 日开始解决,并向前计算 2015 天,将您带到 0028 年 12 月 5 日。
您可以使用 SimpleDateFormat.setLenient(false)
更改此行为 - 禁用宽大处理,它将为超出范围的数字抛出异常。 Calendar.setLenient()
请注意,对于 Java 8 中的新代码,最好避免使用旧的 Date
和 Calendar
类。如果可以,请使用 LocalDateTime.parse(CharSequence text, DateTimeFormatter formatter)
。