adamconkey
adamconkey

Reputation: 4745

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

Upvotes: 0

Views: 88

Answers (2)

Parth Soni
Parth Soni

Reputation: 11648

Use

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

instead of

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500645

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

Upvotes: 6

Related Questions