为什么 SimpleDateFormat 在设计上接受没有字母的字符串作为有效日期格式?

Why SimpleDateFormat accepts strings with no letters as valid date formats by design?

我遇到了 this question,它似乎违反了 SimpleDateFormat class 设计的直觉,因为它是这样的:

I will NOT raise an IllegalArgumentException is the date format you give me has no letters. That means I will accept any kind of symbol garbage and I will return it to you. If the date format has at least one letter I will check if it is valid.

我希望 SimpleDateFormat 会在任何时候将无效日期格式传递给此 class' 构造函数时引发 IllegalArgument 异常。

这是我的测试代码:

try
{
   String s = new SimpleDateFormat("34343434").format(new Date());
   System.out.println(s);
} 
catch (Exception e) 
{
   // no exception here
}

try
{
   String s = new SimpleDateFormat("3434a3434").format(new Date());
   System.out.println(s);
} 
catch (Exception e) 
{
   // Exception, yay!
}

为什么 Oracle/Sun 为 SimpleDateFormat 做出这个决定?感觉违反直觉而且容易出错。

编辑:忘了说:我遇到这种情况是因为我必须验证用户输入的日期格式(不是日期)。

编辑2: 我认为这个问题更适合 https://softwareengineering.stackexchange.com/ 因为我不够清楚它实际上是一个关于设计决策而不是编程的问题:

我想知道一个函数的行为与您的直觉预期不同的原因(假设您正在为要出售的库编写函数)。

正如一些评论所指出的:原因可能是没有给这个函数增加额外的复杂性,并且通过文档或手册,用户将能够避免函数的行为会导致错误的场景使用它的应用程序。此外,复杂性越低意味着交货时间越短。

如果有人告诉我这个问题对程序员网站来说是否更好,我会很高兴,所以它可以移动。

I would expect that SimpleDateFormat will raise an IllegalArgument exception anytime an invalid date format is passed to this class' constructor. [...] Why did Oracle/Sun made this decision for SimpleDateFormat? It feels counterintuitive and too much error-prone.

您似乎没有抓住重点。没有任何字母的 SimpleDateFormat 格式字符串是完全有效的。它的含义是 well documented:

Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.

如果没有字母,没问题。所有符号都只是复制过来。为什么要有一个特例呢?特殊情况使代码更脆弱,更难维护。所有可能的行为都有用并不重要,但它们一致.

是非常有价值的