Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and work.

aviboots(AT)netvision.net.il

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Linux Training
Teach Your Child To Read

BlueHost Web Hosting Black Friday

Bonsai Boy of New York Bonsai Trees and Accessories

DreamCloud The Comfortable Luxury Mattress Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

DreamHost Web Hosting


Disclosure We are a professional Programming & Software Q&A website, that receives compensation from some of the links whose we show you with Information. It means that my content may contain affiliate links.

16,852 questions

22,505 answers

573 users

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
...