开发者

explanation for behavior from SimpleDateFormat

开发者 https://www.devze.com 2023-01-08 06:20 出处:网络
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

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

精彩评论

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

关注公众号