Reputation: 131
for a project at uni i'm doing Home Automation, i need to be able to get date and time as well as setting both of them, i need this for automatic activations of certain functions, currently after seraching the web i have these for setting date and time
Date:
char date[9];
_strdate(date);
std::cout << date << std::endl;
Time:
time_t timer;
struct tm y2k;
double seconds;
y2k.tm_hour = 0; y2k.tm_min = 0; y2k.tm_sec = 0;
y2k.tm_year = 100; y2k.tm_mon = 0; y2k.tm_mday = 1;
time(&timer); /* get current time; same as: timer = time(NULL) */
seconds = difftime(timer,mktime(&y2k));
std::cout<<" seconds since January 1, 2000 in the current timezone" << seconds << std::endl;
What i want to know is is there a better way to do both of these, also how do i set the date and time?
Upvotes: 1
Views: 10575
Reputation: 159
Rather than declaring a struct, declare a class. That way, you can declare all of your data points within, and use getter and setter functions to modify and print them. Write it like this:
class y2k
{
// Private variables
int tm_hour;
int tm_year;
int tm_min;
int tm_mon;
int tm_sec;
int tm_mday;
public:
// Getters
int getHour() {return tm_hour;}
int getYear() {return tm_year;}
int getMin() {return tm_min;}
int getMon() {return tm_mon;}
int getSec() {return tm_sec;}
int getMDay() {return tm_mday;}
// Setters
void setHour(int hour) {hour = tm_hour;}
void setYear(int year) {year = tm_year;}
void setMin(int min) {min = tm_min;}
void setMon(int mon) {mon = tm_mon;}
void setSec(int sec) {sec = tm_sec;}
void setMDay(int mday) {mday = tm_mday;}
};
Use the getters if you choose to print the value to the screen, and the setters if you want to set the data. For instance, if you declared y2k foo
, then you could set the year like so: foo.setYear(100)
.
Upvotes: 0
Reputation: 3302
If you want your date/time code to be portable you might want to consider a library like the Boost date/time library.
This will also give you the ability to do calculations and work with time intervals, etc. and you can concentrate on writing your own code instead of a library of custom date time methods and classes.
There are some contrived examples at http://www.boost.org/doc/libs/1_55_0/doc/html/date_time/examples/general_usage_examples.html
Upvotes: 1