java.util.Date is generating a wrong date?

本小妞迷上赌 提交于 2019-11-28 02:28:49

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.

Peter Lawrey

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
display_name

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");

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!