Detect months with 31 days

前端 未结 19 1665
南旧
南旧 2020-12-18 01:53

Is there an analogous form of the following code:

if(month == 4,6,9,11)
{
  do something;
}

Or must it be:

if(month == 4 ||         


        
19条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-18 02:31

    This month

    System.out.println("This month has " + new GregorianCalendar().getActualMaximum(Calendar.DAY_OF_MONTH) + " days in it.");
    

    if statement to check if there is 31 days on this month

    if (31 == new GregorianCalendar().getActualMaximum(Calendar.DAY_OF_MONTH))
    {
        System.out.println("31 days on this month");
    }
    else
    {
        System.out.println("Not 31 days in this month");
    }
    

    Write number of days for all months

    Calendar cal = new GregorianCalendar();
    for (int i = 0; i < 12; i++)
    {
        cal.set(2009, i, 1); //note that the month in Calendar goes from 0-11
        int humanMonthNumber = i + 1;
        int max = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        System.out.println("The " + humanMonthNumber + ". month has " + max  + " days.");
    }
    

    output:

    This month has 30 days in it.
    Not 31 days in this month
    The 1. month has 31 days.
    The 2. month has 28 days.
    The 3. month has 31 days.
    The 4. month has 30 days.
    The 5. month has 31 days.
    The 6. month has 30 days.
    The 7. month has 31 days.
    The 8. month has 31 days.
    The 9. month has 30 days.
    The 10. month has 31 days.
    The 11. month has 30 days.
    The 12. month has 31 days.
    

提交回复
热议问题