开发者

explanation for behavior from SimpleDateFormat

Try this:

DateFormat df = new SimpleDateFormat("y");
System.out.println(df.format(new Date()));

Without reading the ja开发者_如何学Pythonvadoc for SimpleDateFormat, what would you expect this to output? My expectation was "0". That is to say, the last digit of the current year, which is 2010.

Instead it pads it out to 2 digits, just as if the format string had been "yy".

Why? Seems rather bizarre. If I had wanted 2 digits then I'd have used "yy".


"Without reading the javadoc" is a dangerous attitude more often than not. Joshua Bloch wrote a book on this strange behaviours in Java.


That's why you need to check the documentation:

For parsing with the abbreviated year pattern ("y" or "yy"), SimpleDateFormat must interpret the abbreviated year relative to some century.

"y" is an abbreviation, so this is expected behavior.


If you want only a digit you can:

System.out.println(df.format(new Date()).substring(1));

:)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜