[英]How to obtain hour value from current time in unix (using C)
I have the below program to obtain current date and time. 我有以下程序来获取当前日期和时间。
int main(void)
{
time_t result;
result = time(NULL);
struct tm* brokentime = localtime(&result);
printf("%s", asctime(brokentime));
return(0);
}
And the output of the program is as follows : 该计划的产出如下:
Tue Aug 24 01:02:41 2010
How do I retrieve only the hour value say 01 from the above ? 如何从上面仅检索小时值01?
Or is there any other system call where the currect hour of the system can be obtained ? 或者是否有其他系统调用可以获得系统的当前小时? I need to take an action based on this. 我需要根据这个采取行动。
Thanks 谢谢
struct tm* brokentime = localtime(&result);
int hour = brokentime->tm_hour;
If you want it as a number (and not a string), then just access the appropriate field in the brokentime
structure: 如果您希望它作为数字(而不是字符串),那么只需访问brokentime
结构中的相应字段:
time_t result;
result = time(NULL);
struct tm* brokentime = localtime(&result);
int h = brokentime->tm_hour; /* h now contains the hour (1) */
If you want it as a string, then you will have to format the string yourself (rather than using asctime
): 如果你想将它作为字符串,那么你必须自己格式化字符串(而不是使用asctime
):
time_t result;
result = time(NULL);
struct tm* brokentime = localtime(&result);
char hour_str[3];
strftime(hour_str, sizeof(hour_str), "%H", brokentime);
/* hour_str now contains the hour ("01") */
Use %I
instead of %H
to get 12-hour time instead of 24-hour time. 使用%I
而不是%H
来获得12小时时间而不是24小时时间。
您应该使用tm.tm_hour作为小时值,以及其他(小时,秒,月等)
Struct tm consists of the following. Struct tm包含以下内容。 Some information is not present in the answers above, though they answer the OP perfectly. 上面的答案中没有一些信息,尽管他们完美地回答了OP。
The meaning of each is:
Member Meaning Range
tm_sec seconds after the minute 0-61*
tm_min minutes after the hour 0-59
tm_hour hours since midnight 0-23
tm_mday day of the month 1-31
tm_mon months since January 0-11
tm_year years since 1900
tm_wday days since Sunday 0-6
tm_yday days since January 1 0-365
tm_isdst Daylight Saving Time flag
So you can access the values from this structure. 因此,您可以访问此结构中的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.