[英]Java SimpleDateFormat parsing oddity
I am baffled why this doesn't work. 我很困惑为什么这不起作用。 No matter what I change the day to, it prints out the same thing.
无论我将日期更改为什么,它都会打印出相同的内容。 What is going on here?
这里发生了什么?
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/YYYY");
String s = "11/22/2000";
Date d = sdf.parse(s);
System.out.println(d.toString());
Output: Sun Dec 26 00:00:00 CST 1999
输出:
Sun Dec 26 00:00:00 CST 1999
You're using YYYY
which is the week-year instead of the "normal" year. 您使用的是
YYYY
,它是星期年份,而不是“正常”年份。 That's usually only used with day-of-week and week-of-year specifiers. 通常只与星期几和一年中的指定符一起使用。
The exact behaviour here would be hard to explain - feasible, but not terribly helpful. 这里的确切行为将很难解释-可行,但不是很有帮助。 Basically the solution is "don't do that".
基本上,解决方案是“不要那样做”。 You want a format string of
MM/dd/yyyy
instead - note the case of the yyyy
. 你想要的格式字符串
MM/dd/yyyy
,而不是-注意的情况下, yyyy
。
(As a side note, if you can possibly use java.time.*
from Java 8 or Joda Time, you'll have a lot better time in Java with date/time issues. It wouldn't affect this particular issue, but it's generally a good idea...) (作为附带说明,如果您可以使用Java 8或Joda Time中的
java.time.*
,则在Java中有日期/时间问题的时间会好很多。这不会影响此特定问题,但是通常是个好主意...)
Use 采用
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy")
instead of 代替
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/YYYY");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.