Monday, April 18, 2011

Calendar example code in C/C++

A simple calendar example code. The easiest way is to use "time" library. It simply uses std::time() and std::localtime() to compute date. Calendar example code is shown below.


  1. #include <ctime>
  2. #include <iostream>
  3. int main()
  4. {
  5. std::time_t temp = std::time ( 0 );
  6. std::tm *first = std::localtime ( &temp );
  7. first->tm_year = 2008 - 1900;
  8. first->tm_mday = 1;
  9. first->tm_mon = 0;
  10. if ( std::mktime ( first ) != (std::time_t)-1 ) {
  11. char weekday[100];
  12. if ( std::strftime ( weekday, 100, "%A", first ) > 0 )
  13. std::cout<<"The first day of the year is "<< weekday <<'\n';
  14. }
  15. }