简体   繁体   中英

Java Valid Date Leap Year

This is my updated code, it still doesn't work. It returns day for all cases of Feb. 29th, when it should only return day if it is a leap year, if it is not a leap year 1 should be returned.

public int checkDay (int day)
{
    // For months with 30 days.
    if ((month == 4 || month == 6 || month == 9 || month == 11) && day <= 30)
        return day;
    // For months with 31 days.
    if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (day <= 31))
        return day;
    // For leap years.
    // If February 29th...
    if (month == 2 && day == 29)
    {
        // Check if year is a leap year.
        if ((year%4 == 0 && year%100!=0) || year%400 == 0) 
        {
            // If year is a leap year return day as 29th.
            return day; 
        }
        // If not a leap year, return day as 1st.
        else return 1;
    }
    // If Date if February 1st through 28th return day, as it is valid.
    if (month == 2 && (day >= 1 && day <= 28))
        return day;
// Return day as 1st for all other cases.
return 1;
}

Try GregorianCalendar http://docs.oracle.com/javase/6/docs/api/java/util/GregorianCalendar.html

GregorianCalendar gc = new GregorianCalendar();
if (gc.isLeapYear(year) ) 

尝试将代码更改为

if (year%4==0&&(year%100!=0&&year%400==0)) 
if ((year%4==0 && year%100!=0) || year%400==0)

this solves your problem, your logic was false :)

try this code: if the returned boolean is false you can set the day to 1, because the date is not valid.

public bool checkDay (int day, int month, int year){
    bool valid = false;
    if(day >=1){
        // For months with 30 days.
        if ((month == 4 || month == 6 || month == 9 || month == 11) && day <= 30){
            valid = true;
        }
        // For months with 31 days.
        if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day <= 31){
            valid = true;
        }
        // For February.
        if (month == 2)
        {
            if(day <= 28){
                valid = true;
            } else if(day == 29){
                if ((year%4 == 0 && year%100!=0) || year%400 == 0){
                    valid = true;
                } //else invalid
            }
        }
    } //else date is not valid
    return valid;
}

It is better practice to have only one return statement in each method. That makes it easier to understand the code and by that to debug it and find possible errors. If you have any problems, feel free to ask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM