Check if date is valid or not using C++

In this tutorial, you will learn to check if a given date is valid or not using C++. The concept is easy; check if a year is in a reasonable range (1500 to 2200 in this example), a day is not zero, and a month if it falls in the correct range (January has 31 days, April has 30 days, February can have 28 or 29 days, etc.)

Check if a date is valid or not using C++

First, we need a function to check if a year is a leap or not.

Check leap year in C++

#include <iostream>
using namespace std;

bool IsLeap (int year) {
 
 bool isLeap;

    if (year % 4 == 0) {
        if (year % 100 == 0) {
            if (year % 400 == 0)
              isLeap = true;
            else
               isLeap = false;
        }
        else
           isLeap = true;
    }
    else
    isLeap= false;

    return isLeap;
}

Now we have the function to check for leap year, let’s move to the main function of this tutorial: check if a date is valid to not.

bool isDateValid(int month, int day, int year) {
  bool validation = true;

  // Check if year within range
  if (!(year >= 1500 && year <= 2200))
    validation = false;

  // cehck if day is not less than 1
  if (day < 1)
    validation = false;

  // check the month
  switch (month) {
  case 2: // if February, check leap year
    if (IsLeap(year)) // call another function to check if year is leap or not
      if (day > 29)
        validation = false;
      else
    if (day > 28)
      validation = false;
    break;

  case 1: //January
  case 3: //March
  case 5: //May
  case 7: //July
  case 8: //August
  case 10: //October
  case 12: //December
    if (day > 31)
      validation = false;
    break;
  case 4: //April
  case 6: //Jun
  case 9: //September
  case 11: //November
    if (day > 30)
      validation = false;
    break;
  default:
    validation = false;
    break;
  }
  return validation;
}

Now call the function above:

if (isDateValid(02,77,2022))
{
    cout << year << "Date is valid";
}
else
{
      cout << year << "Date is not valid";
}
Output
Date is not valid

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *