9.8 Header File:Chrono.h
namespace Chrono{
enum class Month{
//...
};
class Date{
//...
};
//helper functions..
File:Chrono.cpp
#include "Chrono.h"
// definitions
add_year function as a member function.
void Date::add_year(int n){
y+=n;
}
How about leapyear? Ex)2016, Feb 29 => 2017, feb 29? Let's choose 2017, mar 1.
void Date::add_year(int n){
if(m==feb && d==29 && !leapyear(y+n)){
m==mar;
d=1;
}
y+=n;
}
bool leapyear(int y){
//
}
bool leapyear(int y)
{
if (y%4) return false;
if (y%100==0 && y%400) return false;
return true;
}
For simplicity, assume (n>0).
void Date::add_month(int n){
//?
}
Hint:
int days_in_month(int y, Month m){
static int days[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
if(int(m)==2 && leapyear(y)) return 29; //handle Feb separately.
else return days[int(m)];
}
ostream & operator<<(ostream & os, const Month m){
static string month_tbl[13]={"","jan","feb","mar","apr","may","jun","july", "aug", "sep", "oct", "nov", "dec"};
os<<month_tbl[int(m)];
return os;
}
ostream & operator<<(ostream & os, const Date & d){
//Month mm=d.month();
os<<d.month()<<"-"<<d.day()<<", "<<d.year();
return os;
}
Assume n>0.
int days_in_month(int y, Month m){
static int days[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
if(int(m)==2 && leapyear(y)) return 29; //handle feb separately.
else return days[int(m)];
}
void Date::add_day(int n){
// Use days_in_month and add_month
}
Hint: Use add_month(1) after reset the day as 1.
n=n+d-1;
d=1;
Problem in add_month.
Feb 29, 2016
-12 mont
Feb 29, 2015 = March 1, 2015
March 1,2015
+12 month
March 1, 2016 (Not same)
In general,
d.add_month(1);
d.add_month(1);
is not equal to
d.add_month(2)
One implementation.
void Date::add_month(int n){
int yy=(n/12);// extra years
int mm=n%12;// extra month
m=Month(int(m)+mm);
y+=yy; //negative year is ok!
if(int(m)>12){
++y;
m=Month(int(m)-12);
}
else if(m <= 0){ //negative month.
m=Month(int(m)+12);
--y;
}
if(d>days_in_month(y,Month(int(m)))){
d-=days_in_month(y,Month(int(m)));//m<=days(m+1) since d=d-days<=3<days(m+1)
m=Month(int(m)+1); //carry over. m<=12 since (m=12 && d>days=31) is always false.
}
}
Hint
n=n+d-1;
d=1;
bool Date::is_date(){
// 1<=m<=12
// 1<=d<=days_of_month
}