C++ Program to Display Current Date and Time

«
»
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.

  1. /*
  2.  * C++ Program to Print Current Date and Time
  3.  */
  4. #include <iostream>
  5. #include <ctime>
  6. #include <iomanip>
  7.  
  8. std::string month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  9.                         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  10. std::string day[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  11.  
  12. int main()
  13. {
  14.     time_t timer;
  15.     tm * time;
  16.     const int BASE_YEAR = 1900;
  17.  
  18.     std::time(&timer);
  19.     time = localtime(&timer);
  20.     std::cout << "Current date " << day[time->tm_wday] << " "
  21.               << month[time->tm_mon] << " " << time->tm_mday
  22.               << " " << (time->tm_year + BASE_YEAR);
  23.     std::cout << "\nCurrent time " << std::setw(2) << std::setfill('0')
  24.               << time->tm_hour << " : " << std::setw(2) << std::setfill('0')
  25.               << time->tm_min << " : " << std::setw(2) << std::setfill('0')
  26.               << time->tm_sec;   
  27. }

$ a.out
Current date Thu Oct 10 2013
Current time 00 : 24 : 50

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.