This C++ program prints the current date and time. The program uses the time library where a time_t structure is initialized to current date and time. The various members of the structure, i.e. current date, day in week, month and year, etc. can be accessed and the date can be printed in any format. The member tm_year is number of years since 1900.
Here is the source code of the C++ program prints the current date and time. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Print Current Date and Time
*/
#include <iostream>
#include <ctime>
#include <iomanip>
std::string month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
std::string day[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
int main()
{
time_t timer;
tm * time;
const int BASE_YEAR = 1900;
std::time(&timer);
time = localtime(&timer);
std::cout << "Current date " << day[time->tm_wday] << " "
<< month[time->tm_mon] << " " << time->tm_mday
<< " " << (time->tm_year + BASE_YEAR);
std::cout << "\nCurrent time " << std::setw(2) << std::setfill('0')
<< time->tm_hour << " : " << std::setw(2) << std::setfill('0')
<< time->tm_min << " : " << std::setw(2) << std::setfill('0')
<< time->tm_sec;
}
$ a.out Current date Thu Oct 10 2013 Current time 00 : 24 : 50
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Check Programming Books
- Check Computer Science Books
- Apply for C++ Internship
- Apply for Computer Science Internship
- Practice Programming MCQs