Created
February 19, 2015 19:54
-
-
Save MartelliEnrico/c56e5c5b48a4e5a8ea25 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Data { | |
protected: | |
int day_, month_, year_; | |
bool valid_; | |
bool isLeapYear(int year) | |
{ | |
return year % 4 == 0; | |
} | |
int daysNumberForMonth(int month, int year) | |
{ | |
switch(month) | |
{ | |
case 4: | |
case 6: | |
case 9: | |
case 11: | |
return 30; | |
case 2: | |
return isLeapYear(year) ? 29 : 28; | |
default: | |
return 31; | |
} | |
} | |
int getDayOfYear() | |
{ | |
int days = day_; | |
for(int i = 1; i < month_; i++) | |
{ | |
days += daysNumberForMonth(month_, year_); | |
} | |
return days; | |
} | |
bool validateDate(int day, int month, int year) | |
{ | |
if(month < 1 && month > 12) // Invalid month | |
return false; | |
if(day < 1 && day > daysNumberForMonth(month, year)) // Invalid day | |
return false; | |
return true; | |
} | |
public: | |
void set(int day, int month, int year) | |
{ | |
valid_ = validateDate(day, month, year); | |
day_ = day; | |
month_ = month; | |
year_ = year; | |
} | |
bool isChristmas() | |
{ | |
return day_ == 25 && month_ == 12; | |
} | |
int diff(Data other) | |
{ | |
int days = 0, start, end; | |
int dayOfYear = getDayOfYear(); | |
int otherDayOfYear = other.getDayOfYear(); | |
if(other.year_ >= year_) | |
{ | |
if(other.year_ == year_ && otherDayOfYear < dayOfYear) | |
{ | |
days = dayOfYear - otherDayOfYear; | |
} | |
else | |
{ | |
days = otherDayOfYear - dayOfYear; | |
} | |
start = year_; | |
end = other.year_; | |
} | |
else | |
{ | |
days = dayOfYear - otherDayOfYear; | |
start = other.year_; | |
end = year_; | |
} | |
for(; start < end; start++) | |
{ | |
days += isLeapYear(start) ? 366 : 365; | |
} | |
return days; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment