0

我在创建日期时遇到问题。

Calendar gc = new GregorianCalendar();
int leto = randBetween(2001, 2020);
gc.set(GregorianCalendar.YEAR, leto);
int dan= randBetween(1, gc.getActualMaximum(GregorianCalendar.DAY_OF_YEAR));
gc.set(GregorianCalendar.DAY_OF_YEAR, dan);
//   System.out.println(gc.get(GregorianCalendar.YEAR) + "-" +
//     gc.get(GregorianCalendar.MONTH) + "-" +
//     gc.get(GregorianCalendar.DAY_OF_MONTH));

public static int randBetween(int start, int end) {
  return start + (int)Math.round(Math.random() * (end - start));
}

我有一个生成日期的函数,但在这个函数中有很多失败。我得到许多未设置 MONTH 值的日期。

31,6,2004 1,7,2004
23,0,2013 24,0,2013
19,0,2008 20,0,2008 
31,9,2014 31,9,2014

但我不知道为什么会这样?

4

1 回答 1

3

此代码不是“失败”,但它没有给出预期的结果。

您看到的日期是:

23,0,2013  -- 23rd of January, 2013.
31,6,2013  -- 31st of July, 2013.

也就是说,month不是从 1 开始的,不像 day,它是从 0 开始的。

请放心,这对于 Java Date API 来说是相当常见的错误,并且可能唯一认为这是合乎逻辑的人就是提出此 API 的人,甚至可能不再是他们......</p>

于 2013-10-25T19:15:16.200 回答