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