Detect months with 31 days

前端 未结 19 1666
南旧
南旧 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:21

    A complete solution, also taking leap year into account.

    private static int getDaysInMonth(LocalDateTime localDateTime) {
    
        int daysInMonth = 0;
        int year = localDateTime.getYear();
        int month = localDateTime.getMonth().getValue();
    
        switch (month) {
            case 1: case 3: case 5:
            case 7: case 8: case 10:
            case 12:
                daysInMonth = 31;
                break;
            case 4: case 6:
            case 9:case 11:
                daysInMonth = 30;
                break;
            case 2:
                if(((year % 4 == 0) && !(year % 100 == 0) || (year % 400 == 0))) {
                    daysInMonth = 29;
                } else {
                    daysInMonth = 28;
                }
                break;
            default: System.out.println("Invalid month");
                break;
        }
    
        return daysInMonth;
    }
    

提交回复
热议问题