How to write class that represent a date in C++

2 Answers

0 votes
#include <iostream>
#include <ctime>

using std::cout;
using std::endl;

class CDate {
private:
	short month, day, year;
public:
	void init(void);
	void init(int m, int d, int y);
	void show(void);
};

void CDate::init(void) {
	struct tm *p;
	time_t sec;
	time(&sec);
	p = localtime(&sec);

	month = (short)p->tm_mon + 1;
	day = (short)p->tm_mday;
	year = (short)p->tm_year + 1900;
}

void CDate::init(int m, int d, int y) {
	month = (short)m;
	day = (short)d;
	year = (short)y;
}

void CDate::show(void) {
	cout << month << '-' << day << '-' << year << endl;
}

int main()
{
	CDate today;
	today.init();
	today.show();

	CDate birthday;
	birthday.init(2, 27, 1966);
	birthday.show();

	CDate d;
	d = today;
	d.show();

	CDate *p = &d;
	p->show();

	CDate &ref = d;
	ref.init(5, 19, 2018);
	d.show();

	return 0;
}

/*
run:

5-20-2018
2-27-1966
5-20-2018
5-20-2018
5-19-2018

*/

 



answered May 20, 2018 by avibootz
edited Jun 6, 2018 by avibootz
0 votes
#include <iostream>
#include <ctime>

using std::cout;
using std::endl;

class CDate {
	int day, month, year;
public:
	CDate(char *str);
	CDate(int _m, int _d, int _y) {
		month = _m;
		day = _d;
		year = _y;
	}

	CDate(time_t t);
	void print() {
		cout << month << '/' << day << '/' << year << endl;
	}
};

CDate::CDate(char *CDate) {
	sscanf(CDate, "%d%*c%d%*c%d", &month, &day, &year);
}

CDate::CDate(time_t t) {
	struct tm *p;

	time(&t);
	p = localtime(&t);

	month = (short)p->tm_mon + 1;
	day = (short)p->tm_mday;
	year = (short)p->tm_year + 1900;
}

int main()
{
	CDate d1("2/27/1966");
	CDate d2(3, 21, 1980); 
	CDate d3(time(NULL));

	d1.print();
	d2.print();
	d3.print();

	return 0;
}


/*
run:

2/27/1966
3/21/1980
6/2/2018

*/

 



answered Jun 2, 2018 by avibootz

Related questions

1 answer 172 views
1 answer 167 views
1 answer 218 views
1 answer 189 views
2 answers 255 views
1 answer 230 views
...