[英]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.假设我有一个用 C 编写的守护程序,它每五分钟左右唤醒一次,如果它的输入队列中有任何内容,则进行一些处理,然后重新进入睡眠状态。 Now suppose there is some processing that it only has to do after a certain (configurable) time--say, 2 pm (and before midnight).
现在假设有一些处理只需要在某个(可配置的)时间之后进行——比如说,下午 2 点(午夜之前)。
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?在 C 中,将当前时间的小时数转换为 int 变量的最快、最好的方法是什么,以便可以轻松地检查它——以确定实际上是否在今天下午 2 点之后?
localtime.当地时间。 See http://linux.die.net/man/3/localtime
见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.调用
localtime(time(NULL))
永远不会起作用。 The return value of time()
is a time_t
, and the first argument of localtime is a time_t*
. time()
的返回值为time_t
,localtime 的第一个参数是time_t*
。 Neither is the accepted answer, nor is the one with printf correct.既不是公认的答案,也不是 printf 正确的答案。
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.这依赖于
localtime()
返回指向 static 存储的指针这一事实。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.