开发者

Java Date oddity

Out of curiosity, why do I receive an IllegalArgumentException for the MONTH in the below test case?

public class Testing {
    public static void main(String args[]) {

      Calendar c = Calendar.getInstance(Locale.getDefault());
      c.setLenient(false);
      Date d = new Date();

      c.set(Calendar.MONTH, Calendar.FEBRUARY);
      c.set(Calendar.DAY_OF_MONTH, 30);
      c.set(Calendar.YEAR, 2010);

      d = c.getTime();  //Exception is not thrown until this line

      System.out.println(d.toString());
    }
}

I looked at the Gre开发者_运维问答gorianCalendar which is the default on my system, and realize that the MONTH field would in fact be the first one to differ in the two Feb 30, vs March 2 in this case, but shouldn't this IllegalArgumentException be what causes the overflow, or was it just deemed to difficult to "discover"?


Because February always has less than 30 days. And you are setting the day on the Calendar instance to 30. So, when you try to create an invalid Date, Java will not let you because that would be an invalid date and you have chosen setLienient(false).

Try the following:

c.set(Calendar.DAY_OF_MONTH, 28);
c.set(Calendar.MONTH, Calendar.FEBRUARY);
c.set(Calendar.YEAR, 2010);

That should work.

This is ultimately caused because you are calling c.setLenient(false);. This causes Java to be strict about the dates it allows.

See the Javadoc for the method:

public void setLenient(boolean lenient)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜