C++ program to check given date is in valid format or not

In this C++ program, we will read date and check whether it is in correct format or not?
[Last updated : February 26, 2023]

Checking whether a given date is in valid format or not

As we know that now a days, there are lot of applications are used on the basis of date calculation so that sometime we need to perform operation on date and need check given date is in valid format or not.

In this program, we will validate the date whether it is in correct format or not.

C++ code to check a given date is in valid format or not

#include <iostream>
using namespace std;

short isValidDate(short dd, short mm, short yy)
{
    if (yy < 0)
        return 1;

    if (mm < 0 || mm > 12)
        return 1;

    if (mm == 2) {
        if (yy % 4 == 0) {
            if (dd > 29 || dd < 0)
                return 1;
        }
        else {
            if (dd > 28 || dd < 0)
                return 1;
        }
    }
    else if (mm == 1 || mm == 3 || mm == 5 || mm == 7 || mm == 8 || mm == 10 || mm == 12) {
        if (dd > 31 || dd < 0)
            return 1;
    }
    else {
        if (dd > 30 || dd < 0)
            return 1;
    }

    return 0;
}

int main()
{
    int ret = 0;

    ret = isValidDate(10, 10, 17);
    if (ret == 0)
        cout << "Given date is valid" << endl;
    else
        cout << "Given date is not valid" << endl;

    ret = isValidDate(10, 15, 17);
    if (ret == 0)
        cout << "Given date is valid" << endl;
    else
        cout << "Given date is not valid" << endl;

    return 0;
}

Output

Given date is valid
Given date is not valid

This program can be used for date validation - to validate number of days in a month, number of months in a year.



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.