Date class problem

Hello ,
Recently I was creating a class called date which has some function. one of these functions add certain number of days to date . My problem was finding an algorithm
to do the task efficiently and simply but I came up with a complicated solution!
Main problem was what happens when numbers of day exceed 31 (30 , 29 , 28 sometimes) i could use another function which add month then . finally I came up with following. Can any body provide a better solution(I dont want to use available libraries however):

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//class interface
enum class Month
{
	jan = 0, feb, mar, apr, may, june, july, aug, sep, oct, nov, dec
};

class Date
{
public:
	class Invalid{};
	int day() const { return d; }
	Month month() const { return m; }
	int year() const { return y; }
	Date(int, Month, int);
	Date();
	void add_day(int);
	void add_month(int);
	void add_year(int);
private:
	int d;
        Month m;
	int y;
	const vector<int>& days_month();
};

//definitions (not all of them of course)
void Date::add_day(int n)
{
	if (n <= 0) throw Invalid{};
	int current = static_cast<int>(m);
	int remaining = 0;
	while(true)
	{
		remaining = days_month()[current] - d;
		if ((d + n) <= days_month()[current])
		{
			d += n;
			break;
		}
		if (n >= (remaining + days_month()[current + 1]))
		{
			add_month(1);
			n -= (remaining + days_month()[current + 1]);
			if (current == 11) current = 0;
			else ++current;
			d = 0;
		}
		else
		{
			add_month(1);
			n -= remaining;
			d = n;
			break;
		}
	}
}

const vector<int>& Date::days_month()
{
	static vector<int> nod(12);
	nod.push_back(31);
	nod.push_back(28);
	nod.push_back(31);
	nod.push_back(30);
	nod.push_back(31);
	nod.push_back(30);
	nod.push_back(31);
	nod.push_back(31);
	nod.push_back(30);
	nod.push_back(31);
	nod.push_back(30);
	nod.push_back(31);
	return nod;
}


And finally how can I handle days which shift the date years(like adding 1254 days!)
Forget about the leap year also!
Last edited on
When I wrote my date class I created a function NextDay() which made it easy to adsd multiple days with a loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void CDate::NextDay ()
{
  m_Day++;
  if (m_Day > DaysInMonth ())
  {
    m_Day = 1;
    m_Month++;
  }
  if (m_Month > 12)
  {
    m_Month = 1;
    m_Year++;
  }
}
void CDate::AddDays (unsigned int num_days)
{
  for (int i = 0; i < num_days; i++)
  {
    NextDay ();
  }
}
Thank you!
You are welcome. :)
Topic archived. No new replies allowed.