Check if a date is a future date or not in C++
Hello, Coders!! In this section, we will discuss how we can check whether a date is a future date or not in C++.
Let’s briefly discuss the Date and Time functions and structure in C++ before diving into our main topic.
Date and Time functions and structure in C++
In C++ there is no standard library for the date and time functions. It inherits the functions and structs for date and time from the C language. We can access all the date and time functions and structures by including the <ctime> standard file in C++.
There are four types of time-related data types that are capable of representing the system’s time and date as an integer. (i.e. tm, size_t, time_t, clock_t)
We can get all the time and date data types in the tm structure, like tm_year(a year since 1900), tm_hour(an hour from 0 to 24), tm_mon(month of the year from 0 to 11), tm_yday(day since 1st January), tm_wday(day since Sunday) etc.
As for the functions, there are a lot of functions for date and time-related operations, but in this article, we will only discuss the time() function which will require later in our program.
The time() function is a C library function that returns the date and time elapsed since January 1, 1970, 00:00:00 UTC.
Syntax:
time_t time(time_t *t)
Program to check if a date is a future date or not in C++
- In this program, we will define a function checkFutureDate() function that will take the year, month, and day as parameters and check whether that date is a future date or not.
#include<iostream>
#include<ctime>
using namespace std;
time_t now = time(0);
tm *ltm = localtime(&now);
bool checkFutureDate(int year, int month, int day) {
if(year > (1900 + ltm->tm_year)) {
return true;
}
else if(year == (1900 + ltm->tm_year)) {
//adding 1900 to get the current year
if(month > 1 + ltm->tm_mon) {
//adding 1 to get the current month
return true;
}
else if(month == 1 + ltm->tm_mon) {
if(day > ltm->tm_mday) {
return true;
}
else {
return false;
}
}
}
}
int main() {
int year,month,day;
cout << "Enter The Date To Check:" << endl;
cout << "Year: ";
cin >> year;
cout << "Month: ";
cin >> month;
cout << "Day: ";
cin >> day;
cout << "You Have Entered: " << day << "/" << month << "/" << year << endl;
bool result = checkFutureDate(year,month,day);
if(result == true) {
cout << "This Is A Future Date" << endl;
}
else {
cout << "This is not a Future Date" << endl;
}
return 0;
}Output-1:
Enter The Date To Check: Year: 2022 Month: 02 Day: 12 You Have Entered: 12/2/2022 This Is A Future Date
Output-2:
Enter The Date To Check: Year: 2021 Month: 11 Day: 01 You Have Entered: 1/11/2021 This is not a Future Date
Hope you have enjoyed reading this article and learned how to check whether a date is a future date or not in C++.
Keep Codding!!
You can also read, Change date format in C++
Leave a Reply