如何使用Java日历获取特定月份的天数?

如何使用Java日历获取特定月份的天数?,java,calendar,Java,Calendar,我正在创建一个简单的程序,允许用户查看他们设置的月份之间的天数 例如从一月到三月 我可以使用以下命令获取当月的当前日期: Calendar.DAY_OF_MONTH 我想要的是如何在当月提供价值 我有一个简单的代码: public static void machineProblemTwo(int startMonth, int endMonth) { int[] month = new int[0]; int date = 2015; fo

我正在创建一个简单的程序,允许用户查看他们设置的月份之间的天数

例如从一月到三月

我可以使用以下命令获取当月的当前日期:

Calendar.DAY_OF_MONTH
我想要的是如何在当月提供价值

我有一个简单的代码:

public static void machineProblemTwo(int startMonth, int endMonth) {

        int[] month = new int[0];
        int date = 2015;

        for(int x = startMonth; x <= endMonth; x++) {
           System.out.println(x + " : " + getMaxDaysInMonth(x,date));
        }

    }

public static int getMaxDaysInMonth(int month, int year){

        Calendar cal = Calendar.getInstance();
        int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH); // how can I supply the month here?

        return days;

    }
publicstaticvoidmachineProblemtwo(intstartmonth,intendmonth){
int[]月=新int[0];
int日期=2015年;

对于(int x=startMonth;x在请求最大值之前,您需要将日历设置为该年和该月,例如

cal.set(year, month, 1);
(或根据David的回答使用日历构造函数。)

因此:

或者,最好使用Joda Time或Java 8:

// Java 8: 1-based months
return new LocalDate(year, month, 1).lengthOfMonth();

// Joda Time: 1-based months
return new LocalDate(year, month, 1).dayOfMonth().getMaximumValue();

(我确信Joda Time一定有一个更简单的选项,但我还没有找到它…

使用
GregorianCalendar
的构造函数,在其中传递年、月和日。不要忘记月份从0到11(1月为0,12月为11)


我们也可以这样做:

private DateTime getNewDate(DateTime date, int dayOfMonth) {
    // first we need to make it 1st day of the month
    DateTime newDateTime = new DateTime(date.getYear(), date.getMonthOfYear(), 1, 0, 0);
    int maximumValueOfDays = newDateTime.dayOfMonth().getMaximumValue();

    // to handle the month which has less than 31 days
    if (dayOfMonth > maximumValueOfDays) {
      newDateTime = newDateTime.dayOfMonth().withMaximumValue();
    } else {
      newDateTime = newDateTime.withDayOfMonth(dayOfMonth);
    }
    return newDateTime;
  }

好的,我尝试了您提供的代码,但当我提供我的值时,比如说我有一个
日历月start=new GregorianCalendar(2015,1,1);
它将返回到28,这是错误的,它应该是31。不要忘记月份从0到11。正如我在回答中所说的。所以1表示二月,而不是一月,28是正确的。如果你想使用从1到12的月份,你可以随时编写
新的格里高利安日历(年,月-1,1)
在方法的第一行。啊,好吧,它就像数组一样。谢谢你的解释。顺便说一句,这同样适用于Jon Skeet的解决方案。也谢谢你解释得很好的答案。:)
public static int numberOfDaysInMonth(int month, int year) {
    Calendar monthStart = new GregorianCalendar(year, month, 1);
    return monthStart.getActualMaximum(Calendar.DAY_OF_MONTH);
}
private DateTime getNewDate(DateTime date, int dayOfMonth) {
    // first we need to make it 1st day of the month
    DateTime newDateTime = new DateTime(date.getYear(), date.getMonthOfYear(), 1, 0, 0);
    int maximumValueOfDays = newDateTime.dayOfMonth().getMaximumValue();

    // to handle the month which has less than 31 days
    if (dayOfMonth > maximumValueOfDays) {
      newDateTime = newDateTime.dayOfMonth().withMaximumValue();
    } else {
      newDateTime = newDateTime.withDayOfMonth(dayOfMonth);
    }
    return newDateTime;
  }