Date class

can someone help me? i cant get the end of the month next day output correctly
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 void Date::setYear(int y)
{
    year=(y>= 1900 && y<4000)?y:0;
}

void Date::setMonth(int m)
{
    month=(m>= 1 && m<=12)?m:0;
}

void Date::setDay(int d)
{
    day=(d>= 1 && d<31)?d:0;
}
bool Date::isleapYear()
{
    if( (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) )
        return true;
    else
        return false;

}

void Date::nextDay()
{
    //31 days
        if( (month == 1 || month == 3  || month == 5 || month == 7 ||
         month == 8 || month == 10 ) && day == 31 )
    {
        month++;
        day = 30;
    }
    //30 days
    else if( (month == 4 || month == 6  || month == 9 || month == 11)
                && day == 30)
    {
        month++;
        day = 31;
    }
    //Leap year
    else if( isleapYear() && month == 2 && day == 29 )
    {
        month = 3;
        day = 1;
    }
    // Not Leap Year
    else if( !isleapYear() && month == 2 && day == 28)
    {
        month = 3;
        day = 1;
    }
    // Regular day
    else
        day++;
}
Something like this, perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
struct date
{
  int day ; // 1 ...
  int month ; // jan == 1
  int year ; // 1900 ..

  static bool is_leap( int year ) ;
  bool valid() const ; // return true if day, month, year constitute a valid date

  date& next_day() ;
  static bool last_day_in_month( int month, int year ) ;

  // ...
};

bool date::last_day_in_month( int month, int year )
{
    if( month == 2 ) return is_leap(year) ? 29 : 28 ;

    if( month == 1 || month == 3  || month == 5 || month == 7 ||
        month == 8 || month == 10 || month == 12 ) return 31 ;

    return 30 ;
}

date& date::next_day()
{
   assert( valid() ) ; // if this fails, there was a bug in our earlier code

   if( day < last_day_in_month( month, year ) ) ++day ;

   else // last day in month, roll over to next month
   {
       day = 1 ;
       if( month == 12 ) { month = 1 ; ++year ; } // december, roll over to next year
       else ++month ;
   }

   assert( valid() ) ; // if this fails, there is a bug in our next_day implementation
   return *this ;
}


Consider making month an enumerated type. eg.
enum month_t { Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec } ;
Then, we wont have to worry about the month being invalid.
Topic archived. No new replies allowed.