a Java puzzler

I’m a fan of Java Puzzlers and came across this one on my own. Perhaps it has been brought up before though. What happens when you run this program? Hopefully I can explain the answer by tomorrow!

public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = sdf.parse("1957-02-29");
System.out.println("success: " + d.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}

Explore posts in the same categories: Java

2 Comments on “a Java puzzler”

  1. ksjohnson Says:

    1957 is not a leapyear, so February 29 “rolls over” to March 1. Try 1960, that’s a leap year, so February 29 is valid.

    Although that does seem like something that would throw an Exception, rather than quietly roll to the closest real date. But it’s probably for compatibility, like if someone’s birthday is on February 29. Doesn’t make sense for every application to have to say “Yes, it’s ok, roll to March 1.”

  2. aviadbd Says:

    It’s not about a leap year or about any date in particular. It’s just the implementation of the parse method.

    Try: 1957-04-33 Get: success: Fri May 03 00:00:00 IDT 1957

    Try: 1957-05-40 Get: success: Sun Jun 09 00:00:00 IDT 1957

    Try: 1957-20-40 Get: success: Tue Sep 09 00:00:00 IST 1958


Leave a comment