C++ Program for Date Month Year

Hey there! Welcome to another programming post here on geekstocode. In this post, we are going to discuss one of the most asked programming question.. C++ program for date, month and year. We can interpret this program in many forms. In this post we are basically going to see three of its forms.  

Also read C program for Sum of digit of a number.

Hence, without much delay, let’s get our coding brains to use and get started! 

C++ Date and Time

The C++ standard library does not provide a proper date type for executions with date and time. Hence, C++ inherits the structs and functions for date and time manipulation from C. For accessing the functions related to date and time, you need to include header file in your C++ program.

Hence, you could use these four time-related types: clock_t, time_t, size_t, and tm.
The types – clock_t, size_t and time_t represent the system time and date as some sort of integer.
The structure type tm holds the date and time as a C structure having the following elements −


struct tm {
int tm_sec; // seconds of minutes from 0 to 61
int tm_min; // minutes of hour from 0 to 59
int tm_hour; // hours of day from 0 to 24
int tm_mday; // day of month from 1 to 31
int tm_mon; // month of year from 0 to 11
int tm_year; // year since 1900
int tm_wday; // days since sunday
int tm_yday; // days since January 1st
int tm_isdst; // hours of daylight savings time
}

Libraries:

For your usage and knowledge, I have listed the important functions, which we use while working with date and time in C or C++. Moreover, these functions are part of standard C and C++ library. And you can check their details using references to C++ standard library given below.

Tabulation of functions and libraries:

Sr.NoFunction & Purpose
1time_t time(time_t *time);This particular function returns the current calendar time of the system in number of seconds elapsed since January 1, 1970.

If the system has no time, . Then, it will return 1.
2char *ctime(const time_t *time); Now this one will return a pointer to a string. And it will of the form day month year hours:minutes:seconds year\n\0.
3struct tm *localtime(const time_t *time); This function will also return a pointer. But, it returns a pointer to the tm structure representing local time.
4clock_t clock(void); You can use this to return a value that approximates the amount of time the calling program has been running.

Thus, it will return 1 when the time is not available.
5char * asctime ( const struct tm * time );This returns a pointer to a string that contains the information stored in the structure. And is pointed to by time converted into the form: day month date hours:minutes:seconds year\n\0
6struct tm *gmtime(const time_t *time);This will return a pointer to the time in the form of a tm structure.

Additionally, the time is represented in Coordinated Universal Time (UTC), which is essentially Greenwich Mean Time (GMT).
7time_t mktime(struct tm *time);This returns the calendar-time equivalent of the time found in the structure pointed to by time.
8double difftime ( time_t time2, time_t time1 );This function calculates the difference in seconds between time1 and time2.
9size_t strftime();This function can be used to format date and time in a specific format.
Libraries for Date and Time in C++

C++ programs for Date, Month and Year: 

In this post we are going to discuss three different variations of this program. The first one will be one of the basic ones. Therefore, you will find it the easiest to execute.

Then, we will move onto a little more modified version in which we will display the next day’s details. Hence, it will help you learn a completely different code using the same concept.

Finally, we will go through the program in which we will use the libraries as we have mentioned above. This will be the most compact and efficient method.

Now, when you got the overview of our plan, let us get to the programs right away.

C++ Program to display user entered date, month and year

Algorithm:

  1. Start
  2. Declare the class date.
  3. Then, declare the private data members dd, mm and yy for day, month and year respectively.
  4. And, declare public functions input() and display().
  5. After that, define input() function to take user input on day, month and year. 
  6. Define display() function to display the date.
  7. Finally, define the main function.
  8. Create a date object d.
  9. Then call both input() and display().
  10. Stop. 

Program:

// C++ program to display the entered date, month, and year. 
#include<iostream>
using namespace std;
class date
{
        private:
                        int dd,mm,yyyy;
        public:
                void input();
                void display();
};
void date::input()
{
        cout<<"Enter Year:";
        cin>>yyyy;
        cout<<"Enter Month:";
        cin>>mm;
        cout<<"Enter Day:";
        cin>>dd;
}
void date::display()
{
        cout<<"Today's Date in dd/mm/yyyy format:"<<dd<<"/"<<mm<<"/"<<yyyy;
}
int main ()
{
 date d;
 d.input();
 d.display();
}

Program Explanation:

The above set of codes need little or no explanation because of its simplistic approach. Here we are creating a class for most executions.

First, in the class date we are declaring the member functions and data members as we have specified in the algorithm above.

Then, we take the input of the date from the user using the input() function. After that, we write the display() function for showing the output.

Finally, we move to the main function where we create the date object to call the two functions. 

In addition to the code we have written above, you can modify it in many ways. For instance, you can display the output in terms of strings rather than the dd/mm/yy format. However, you have to use if else block for the same. 

Since, it is the basic approach, you can modify it in many ways. 

Output:

The program we just executed gives the following output:

Output for displaying user entered date
Output for user entered date.

C++ Program to display the next day’s date, month and year.

Algorithm:

  1. Start.
  2. Declare main function.
  3. Then declare the variables dd, mm, yy for date, month and year respectively.
  4. After that, take user input for the same. 
  5. Now, check if the day is 28 and month is 2 for checking February.
  6. If the nested if results true, check for leap year condition.
  7. Else, initialize dd as 1 and mm as 3.
  8. Since, it is not February, increment dd by 1.
  9. Then check for the last day of February, i.e if dd= 29.
  10. If yes, then check if mm= 2. 
  11. And if it is true, initialise dd as 1 and mm as 3.
  12. Or else, increment dd by 1.
  13. Then, check for the last day of April, June, September and November, i.e if dd= 30.
  14. If yes, check for mm.
  15. Then increment dd by 1.
  16. Or else, initialise dd as 1 and increment mm by 1.
  17. Now check if dd= 31.
  18. And check for last month of the year.
  19. If it exceeds, increment yy by 1.
  20. And initialise mm as 1.
  21. Or else increment mm by 1.
  22. For printing the result, check if dd, mm should be preceded by 0.
  23. Print the dd, mm and yy as the result.
  24.    Stop.

Program:

// C++ program to display next day’s day, month and year.
#include <iostream>
using namespace std;
int main()
{
	int dd, mm, yy;
	cout << "Enter today's date in the format:DD MM YYYY\n";
	cin >> dd >> mm >> yy;
	if (dd > 0 && dd < 28)	//checking for day from 0 to 27
		dd += 1;
	if (dd == 28)
	{
		if (mm == 2)	//checking for February

		{
			if ((yy % 400 == 0) || (yy % 100 != 0 || yy % 4 == 0))	//leap year check in case of feb
			{
				dd = 29;
			}
			else
			{
				dd = 1;
				mm = 3;
			}
		}
		else	//when it is not February
			dd += 1;
	}
	if (dd == 29)	//last day check for February

	{
		if (mm == 2)
		{
			dd = 1;
			mm = 3;
		}
		else
			dd += 1;
	}
	if (dd == 30)	//last day check for April, June,September,November
	{
		if (mm == 1 || mm == 3 || mm == 5 || mm == 7 || mm == 8 || mm == 10 || mm == 12)
			dd += 1;
		else
		{
			dd = 1;
			mm += 1;
		}

	if (dd == 31)	//last day of the month
	{
		dd = 1;
		if (mm == 12)	//checking for last day of the year
		{
			yy += 1;
			mm = 1;
		}
		else
			mm += 1;
	}
	cout << "Tomorrow's date:\n";
	if (dd < 10)	//checking if day needs to be preceded by 0
	{
		cout << "0" << dd << " ";
	}
	else
		cout << dd << " ";
	if (mm < 10)	//checking if month needs to be preceded by 0
	{
		cout << "0" << mm << " ";
	}
	else
		cout << mm << " ";
	cout << yy;
	return 0;
}


Program Explanation:

This program is a bit longer and confusing so to understand better let us go through the detailed explanation. 

Since the user can input date in various ways, we have specified the input format at first. Thus, we have asked the user to enter in such a way that we can work on day, month and year separately. 

Next, we check the first condition, i.e if the day is less than 27, then irrespective of month and year we increment the day by 1 and month and year remain the same. 


Then we will check if the month if February and then move on to check if it is a leap year or not. Then we set the date accordingly.


If it’s Feb then we increase the month by 1 and we set day to 1 otherwise simply increment the day by 1.



Then, for January, March, May, July, August, October, and December, we will simply increment the day by 1 otherwise we will increment the month by 1 and set the date to 1.

Finally, if this condition of day = 31 is true then we will set the day to 1. Further, we will check if month is December as then we will set the month to 1 and increment the year by 1 otherwise we will just increment the month by 1.

After setting the date, we will print it and before printing day and month we will check if they need to be preceded by a 0 or not.

Output:

The program we just executed gives the following output:

Output for next day's date
Output for next day’s date.

C++ Program to display the date, month and year using in built functions

Algorithm:

  1. Start.
  2. First, call the ctime library.
  3. Declare main function.
  4. Then, in the function set the time_t cu variable as the current time. 
  5. After that, convert the time to string.
  6. Then, print the local time.
  7. Now for the structure for UTC.
  8. First declare a tm pointer gmtm and assign the current time.
  9. Then, assign dd to the asctime function.
  10. Finally, print the UTC date and time as result.
  11. Stop.

Program:

//C++ Program to display the date, month and year using in built functions
#include <iostream>
#include <ctime>

using namespace std;

int main() {
   // current date/time based on current system
   time_t cu = time(0);
   
   // convert now to string form
   char* dd = ctime(&cu);

   cout << "The local date and time is: " << dd << endl;

   // convert now to tm struct for UTC
   tm *gmtm = gmtime(&cu);
   dd = asctime(gmtm);
   cout << "The UTC date and time is:"<< dd << endl;
}

Program Explanation:

The above code uses the date and time library as we have explained earlier. Therefore, to understand it properly go through the libraries first. 

To go through the procedure we have followed, let us go through the explanation.

At first, we made sure to include the ctime library so that we can easily call the library functions.

 In the main function, we have used the time_t mktime(struct tm *time); function to get the current date and time. 

Then, in order to print the date and time in the string form, we convert it accordingly.

After that, we have converted the date and time to UTC format. For this, we have used struct tm *gmtime(const time_t *time); library function. 

Finally, we have displayed the result. 

Output:

The program we just executed gives the following output:

Output using libraries
Output using libraries

Ending note :

In conclusion, date and time is one of the important concepts in C++ and programming in general. Learning this, you will be able to solve many coding challenges. And, this will also help you in your interview questions. 

Still have doubts or queries? Just ask away. We are here to help.

See you in our next post!

Leave a Comment

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