C++判斷日期有效性


在網上看到很多關於日期有效性的判斷,其中很多都有漏洞,本篇文章的代碼是我在做題時寫的,經過本人測試,個人認為還是很全面的。

當然還有像什么輸入日期為小數或字符等不合法的情況,我沒有做判斷,如果大家感興趣可以自行研究

#include<iostream>
using namespace std;
class Date
{
public: int  mon, day, year;   //月日年
        static int Maxdays[13];//每月最大日期
public:
    Date(int = 2020, int = 1, int = 1);
    bool isDate();     //判斷日期合法性 
    bool isLeapYear(); //判斷閏年
};
int Date::Maxdays[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };

int main()
{
    Date d(2007, 2, 29);
    cout << boolalpha;
    cout << d.isDate();
    return 0;
}
Date::Date(int y, int m, int d) { mon = m; year = y; day = d; }
bool Date::isDate() {
    if (mon < 1 || mon>12) // 無效月 
    {
        return false;
    }
    if (year < 0) // 無效年(年的有效性不好界定,就認為小於0為無效)
    {
        return false;
    }
    if (mon == 2 && day == 29 && isLeapYear())  //閏年2月29日
    {
        return true;
    }
    if (day<1 || day>Maxdays[mon])// 無效日 
    {
        return false;
    }
    return true; //日期有效,返回真
}

bool Date::isLeapYear()
{
    if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
    {
        return true;
    }
    return false;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM