简体   繁体   中英

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

You're using YYYY which is the week-year instead of the "normal" year. 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 .

(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...)

Use

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy")

instead of

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/YYYY");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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