1

Here's my code:

java.util.Date TODAY = new java.util.Date();     
SimpleDateFormat SDF = new SimpleDateFormat( "YYYY-MM-DD" );
System.out.println ( SDF.format( TODAY ) );'

And the result is:

2015-02-33

But today's date is 2015-02-02!

What may be the reason behind this wrong output?

Tom
  • 16,842
  • 17
  • 45
  • 54
sr1
  • 251
  • 4
  • 11

3 Answers3

5

You want to use the yyyy year and dd day of the month.

However, I suggest you migrate to JSR-310 which is built into Java 8 and available for earlier versions of Java. The same code is

System.out.println(LocalDate.now());

prints

2105-02-02
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    I concur. I tend to prefer `LocalDate.now(ZoneId.systemDefault())` to make explicit that getting today’s date is a time zone dependent operation and that you have made a choice of time zone to use. – Ole V.V. Jul 07 '17 at 08:51
2

What may be the reason behind this Wrong Output ?

Your assumptions about the date format string are wrong, the output is correct.

y   Year
Y   Week year
D   Day in year
d   Day in month
M   Month in year
m   Minute in hour

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Y Week year will usually give incorrect results around new year. D will give incorrect results from February. So your format appeared fine most of last month.

weston
  • 54,145
  • 21
  • 145
  • 203
1

When format for SimpleDateFormat is specified as follows:

SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
  • the YYYY - means week year,
  • the MM - means month,
  • the DD - means day in year.

Week year here is not what you wanted. See what is week year.

Your today's date is 2015-02-02, which means that it is 32 days since the beginning of the year 2015 passed and your are on the 33 day. That is why you get date "2015-02-33".

To mean year (and not week year) and day in month change format to SimpleDateFormat("yyyy-MM-dd");

weston
  • 54,145
  • 21
  • 145
  • 203