C++ Exercises: Current date and time
C++ Date: Exercise-1 with Solution
Write a C++ program to get the current date and time.
Sample Solution-1:
C++ Code:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
// current date and time in current system
time_t current_dt = time(0);
// convert date time to string format
char* result = ctime(¤t_dt);
cout << "The current date and time is:\n" << result << endl;
}
Sample Output:
The current date and time is: Tue Mar 15 14:28:05 2022
N.B.: The result may vary for your current system date and time.
Flowchart:

Sample Solution-2:
C++ Code:
#include <iostream>
#include <ctime>
using namespace std;
int main ()
{
time_t crtime;
struct tm * time_info;
char result[80];
time (&crtime);
time_info = localtime(&crtime);
strftime(result,sizeof(result),"%d-%m-%Y %H:%M:%S",time_info);
cout << result;
return 0;
}
Sample Output:
15-03-2022 12:15:31
N.B.: The result may vary for your current system date and time.
Flowchart:

C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: C++ Date Exercises Home.
Next: Get the day of the week from a given date.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join