简体   繁体   English

为什么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"));
    }
}

why this returns Sun Dec 05 00:00:00 GMT 28 I am expecting an exception. 为什么这会返回Sun Dec 05 00:00:00 GMT 28我期待一个例外。

The Javadoc for SimpleDateFormat has this to say about repeated pattern letters: SimpleDateFormat的Javadoc有关于重复模式字母的说法:

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 对于解析,除非需要分隔两个相邻字段,否则将忽略模式字母的数量

(Emphasis mine) (强调我的)

So for parsing , "yyyy-MM-dd" is equivalent to "yMd" . 因此, 对于解析"yyyy-MM-dd"相当于"yMd"

With this pattern, "23-06-2015" is parsed as year = 23, month = 6, dayOfMonth = 2015 . 使用此模式, "23-06-2015"被解析为year = 23, month = 6, dayOfMonth = 2015

By default, this gets resolved by starting at 1st June 0023, and counting 2015 days forward, taking you to 5th December 0028. 默认情况下,从0023年6月1日开始计算,并计算2015年前的日期,将您带到0028年12月5日。

You can change this behaviour with SimpleDateFormat.setLenient(false) -- with leniency disabled, it will throw an exception for out-of-range numbers. 您可以使用SimpleDateFormat.setLenient(false)更改此行为 - 禁用lenalent时,它将为超出范围的数字引发异常。 This is properly documented in Calendar.setLenient() 这在Calendar.setLenient()有适当的记录


Note, for new code in Java 8, it's a good idea to avoid the old Date and Calendar classes. 请注意,对于Java 8中的新代码,避免使用旧的DateCalendar类是个好主意。 Use LocalDateTime.parse(CharSequence text, DateTimeFormatter formatter) if you can. 如果可以LocalDateTime.parse(CharSequence text, DateTimeFormatter formatter)请使用LocalDateTime.parse(CharSequence text, DateTimeFormatter formatter)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM