Advertisement
Guest User

pinkeen

a guest
Oct 12th, 2009
516
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include "date.h"
  2.  
  3. Date::Date(int _month, int _day, int _year):year(_year),month(_month),day(_day)
  4. {
  5.     setMonth(_month);
  6.     setDay(_day);
  7. }
  8.  
  9. bool Date::isLeapYear(int year)
  10. {
  11.     if(year % 400 == 0)
  12.         return true;
  13.  
  14.     if(year % 100 == 0)
  15.         return false;
  16.  
  17.     if(year % 4 == 0)
  18.         return true;
  19.  
  20.     return false;
  21. }
  22.  
  23. int Date::getMonthLength(int month, int year)
  24. {
  25.     int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  26.  
  27.     if(isLeapYear(year))
  28.         days[1] = 29;
  29.  
  30.     return days[month - 1];
  31. }
  32.  
  33. void Date::setMonth(int _month)
  34. {
  35.     month = _month;
  36.     if(month < 0 || month > 12)
  37.     {
  38.         std::cerr << "Invalid month: " << month << " (in date: " << *this << ")" <<  std::endl;
  39.         month = 1;
  40.     }
  41.  
  42.     // Day should be re validated when year or month is changed
  43. };
  44.  
  45. void Date::setDay(int _day)
  46. {
  47.     day = _day;
  48.  
  49.     if(day < 0 || day > getMonthLength(month, year))
  50.     {
  51.         std::cerr << "Invalid day: " << day << " (in date: " << *this << ")" <<  std::endl;
  52.         day = 1;
  53.     }
  54. }
  55.  
  56. void Date::setYear(int _year)
  57. {
  58.     year = _year;
  59. }
  60.  
  61. void Date::print()
  62. {
  63.     std::cout << month << "/" << day << "/" << year << std::endl;
  64. }
  65.  
  66. int Date::getMonth() { return month; };
  67. int Date::getDay() { return day; };
  68. int Date::getYear() { return year; };
  69.  
  70. std::ostream &operator<<(std::ostream &stream, Date &date)
  71. {
  72.     stream << date.month << "/" << date.day << "/" << date.year;
  73. }
  74.  
  75. int main()
  76. {
  77.     Date a(13, 23, 2009);
  78.     Date b(6, 30, 1994);
  79.     Date c(2, 29, 2009);
  80.  
  81.     std::cout << "Date a is: ";
  82.     a.print();
  83.     std::cout << "Dates b - c are: ";
  84.     std::cout << b << " - " << c << std::endl;
  85.  
  86.     std::cout << "Date c year is " << c.getYear() << std::endl;
  87.  
  88.     b.setMonth(1);
  89.     c.setDay(27);
  90.    
  91.     std::cout << "Dates are now:" << std::endl;
  92.     std::cout << "a: " << a << " b: " << b << " c: " << c << std::endl;
  93. }
  94.  
  95.  
Advertisement
RAW Paste Data Copied
Advertisement