javadatetimesimpledateformat

explanation for behavior from SimpleDateFormat


Try this:

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

Without reading the javadoc 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".


Solution

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