简体   繁体   English

java.util.Date生成错误的日期?

[英]java.util.Date is generating a wrong date?

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 2015-02-33

But today's date is 2015-02-02! 但是今天的日期是2015-02-02!

What may be the reason behind this wrong output? 输出错误的原因可能是什么?

You want to use the yyyy year and dd day of the month. 您要使用月份的yyyy年和dd日。

However, I suggest you migrate to JSR-310 which is built into Java 8 and available for earlier versions of Java. 但是,我建议您迁移到Java 8中内置的JSR-310,该版本可用于Java的早期版本。 The same code is 相同的代码是

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

prints 版画

2105-02-02

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 http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Y Week year will usually give incorrect results around new year. Y星期年通常会在新年前后给出错误的结果。 D will give incorrect results from February. D将从2月开始给出错误的结果。 So your format appeared fine most of last month. 因此,您的格式在上个月的大部分时间里都很好。

When format for SimpleDateFormat is specified as follows: 当指定SimpleDateFormat的格式如下时:

SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
  • the YYYY - means week year , YYYY-表示星期年
  • the MM - means month, MM-表示月份,
  • the DD - means day in year . DD一年中的一天

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 . 您今天的日期是2015年2月2日 ,这意味着距2015年年初已过去32天 ,而您的日期是33天 That is why you get date "2015-02-33" . 这就是为什么您获得日期“ 2015-02-33”的原因

To mean year (and not week year) and day in month change format to SimpleDateFormat(" yyyy -MM- dd "); 要表示 (而不是周年)和月中的某日,请将格式更改为SimpleDateFormat(“ yyyy -MM- dd ”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM