Java中SimpleDateFormat的模式与参数不同

3

SimpleDateFormat的格式为"yyyyMM",而参数为"yyyy-MM",但是没有异常抛出并且结果错误。为什么呢?谢谢~~

SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
System.out.println(format.format(format.parse("2011-07")));

结果为201105


1
有点奇怪,但它似乎正确获取了年份,然后将月份设为-7,因此12-7=5。 - Blem
1
@Blem: 正确。如果你查看源代码,甚至有特殊的逻辑来识别阿拉伯文中的负号(它们放置在数字之后)。 - Michael Borgwardt
2个回答

4

使用setLenient(false);这将会抛出您期望的异常。

请参阅setLenient()文档


0

parse 的输入有误,请尝试

System.out.println(format.format(format.parse("201107")));

在2011-07中,它将月份解释为负7个月,导致结果为201005(12-7=5)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接