0

I am using C++. I want to get computer time (I know how to do with ctime function). I want to take time like a int variable (sec, min, etc.). Any help?

Something like: int sec = get.sec(); int min = get.min();

I don`t want a time_t variable.

ChrystianSandu
  • 73
  • 1
  • 1
  • 9
  • It might be operating system specific. – Basile Starynkevitch Jan 04 '15 at 17:01
  • 1
    It looks like you haven't done any research. // Closed as duplicate. The linked question has something that gives you seconds since the epoch. – Sebastian Mach Jan 04 '15 at 17:07
  • 1
    Have you googled for `c++ time`? The first link was to (time)[http://www.cplusplus.com/reference/ctime/time/] with references to the (`gmtime`)[http://www.cplusplus.com/reference/ctime/gmtime/] function at the bottom. It looks like the `tm` struct has what you are looking for. – Andrew Monshizadeh Jan 04 '15 at 17:08

1 Answers1

4

In C++11 you could use <chrono>. You might also use time(2), localtime(3), strftime(3), clock(3), clock_gettime(2) (if your system have them). Probably

 time_t now=0;
 time(&now);
 char nowbuf[64];
 strftime(nowbuf, sizeof(nowbuf), "%c", localtime(now));

might be relevant if you want some string. Otherwise, notice that localtime returns a pointer to a struct tm which has many numerical fields. e.g.

struct tm* lt = localtime(now);
int hours = lt->tm_hour;
int minutes = lt->tm_min;

Of course, in principle you should need to test against failure of time, localtime etc... (but I never had these functions fail).

Details are usually operating system specific. If on Linux, read time(7); some framework libraries like POCO or Qt might provide a common (OS independent) abstraction above them.

BTW, you may or not care about time zones and you might want gmtime instead of localtime.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • Well, yes, but I want something like this: int sec = get.sec(); int min = get.min(); – ChrystianSandu Jan 04 '15 at 17:07
  • now, must be a struct :) – ChrystianSandu Jan 04 '15 at 17:14
  • What must be a `struct`? `now` (passed to `time(&now)` ...) is defined as `time_t now=0;` and is a numerical type (an integral type on every system I know of). – Basile Starynkevitch Jan 04 '15 at 17:16
  • int main() { time_t timer; struct tm y2k; double seconds; y2k.tm_hour = 0; y2k.tm_min = 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)); printf ("%.f seconds since January 1, 2000 in the current timezone", seconds); return 0; } – ChrystianSandu Jan 04 '15 at 17:16