Tags:
create new tag
view all tags

Hands on Date object.

Goal

Create and augment a Date class.

Steps

  1. Create and run the following date class below.
  2. Write a Date methods that set and get the day of month of the day.
  3. Write a Date method that set and get the year of the date.
  4. Write a Date method that returns the number of days remaining in a month.
  5. Can you write a function that compares to dates? How?

The Date Class

The Date.h header

#include <iostream>

using namespace std;

class Date
{
 public:
    Date ();
    Date ( int mn, int day, int yr);  // constructor
    void display();                   // function to display date
    int GetMonth();
    void SetMonth(int mn);
 private:
    int month, day, year;
    int DaysSoFar();
};
 

Date.cpp

// constructor definition
#include "Date.h"
 Date::Date ()
{
   month = day = year = 1;
}

Date::Date (int mn, int dy, int yr)
{
   static int length[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

   month = max(1, mn);
   month = min(month,12);

   day = max(1,dy);
   day = min(day, length[month]);

   year = max(1, yr);
}

void Date::display()
{
   static string name[] = {"nothing", "January", "February", "March", "April",
            "May", "June", "July", "August", "September", "October",
            "November", "December" };

   cout << '\n' << name[month] << ' ' << day << "," << year << '\n';
   cout << "Days so far: " << DaysSoFar() << '\n';
}

int Date::DaysSoFar()
{
   int total = 0;
   static int length[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

   for (int i=1; i < month; i++) total += length[i];
   total += day;
   return (total);
}

int Date::GetMonth()
{
   return month;
}

void Date::SetMonth(int mn)
{
   month = max(1, mn);
   month = min(month, 12);
}
 

The Date test code

#include <iostream>
#include "Date.h"

using namespace std;

int main()
{
   Date mydate(1, 2, 1993);
   Date date2(4,11,2018);
   Date date3;

   Date date4(34,25,2034);

   mydate.display();
   date2.display();
   date3.display();
   date4.display();

}
 
Topic revision: r1 - 2018-03-27 - JimSkon
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2018 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback