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
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification 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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.