Date Class Implementation in C++

This C++ program implements a class – Date. The class uses time header contains a function time() which returns current calender time as an object of type time_t. We can extract various information from this struct by using -> with the pointer to the time structure.

Here is the source code of the C++ program implements a class – Date. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to implement Class Date
  3.  */
  4. #include <iostream>
  5. #include <ctime>
  6.  
  7. std::string months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  8.                         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  9. std::string days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri",
  10.                       "Sat"};
  11.  
  12. class Date{
  13.     // Private Members
  14.     private:
  15.         std::string month;
  16.         std::string day;
  17.         int date;
  18.         int year;
  19.     // Public Members
  20.     public:
  21.         // Default Constructor
  22.         Date() { 
  23.                 const int BASE_YEAR = 1900;
  24.                 time_t timer;
  25.                 tm * time;
  26.                 std::time(&timer);
  27.                 time = localtime(&timer);
  28.                 date = time->tm_mday;
  29.                 month = months[time->tm_mon];
  30.                 day = days[time->tm_wday];
  31.                 year = time->tm_year + BASE_YEAR;
  32.         }
  33.         void printDate(void) { 
  34.             std::cout << "Current date " 
  35.                       << this->month << " " << this->day << " "
  36.                       << this->date  << " " << this->year;
  37.         }
  38.         // Destructor
  39.         ~Date() {}
  40. };
  41.  
  42. int main()
  43. {
  44.     Date d;
  45.  
  46.     d.printDate();
  47. }

$ a.out
Current date Oct Mon 7 2013

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

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

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 & discussions at Telegram SanfoundryClasses.