简体   繁体   中英

Getting the current hour in C using time.h

Total newbie question here; I apologize in advance.

Suppose I have a daemon written in C that wakes itself up every five minutes or so, does some processing if there's anything in its input queue, and then goes back to sleep. Now suppose there is some processing that it only has to do after a certain (configurable) time--say, 2 pm (and before midnight).

In C, what is the quickest, best way to get the current time's hour into an int variable, so that it can easily be checked against--to determine if, in fact, it is after 2pm on today?

localtime. See http://linux.die.net/man/3/localtime

time_t now = time(NULL);
struct tm *tm_struct = localtime(&now);

int hour = tm_struct->tm_hour;

The call localtime(time(NULL)) will never work. The return value of time() is a time_t , and the first argument of localtime is a time_t* . Neither is the accepted answer, nor is the one with printf correct.

time_t now;
struct tm *now_tm;
int hour;

now = time(NULL);
now_tm = localtime(&now);
hour = now_tm->tm_hour;
printf("the hour is %d\n", localtime(time(NULL))->tm_hour);

This relies on the fact that localtime() returns a pointer to static storage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM