如何在unix中从当前时间获取小时值(使用C)
我有以下程序来获取当前日期和时间如何在unix中从当前时间获取小时值(使用C),c,unix,C,Unix,我有以下程序来获取当前日期和时间 int main(void) { time_t result; result = time(NULL); struct tm* brokentime = localtime(&result); printf("%s", asctime(brokentime)); return(0); } 程序输出如下: Tue Aug 24 01:02:41 2010 如何仅从上面检索小时值,例如01? 或者是否有其他
int main(void)
{
time_t result;
result = time(NULL);
struct tm* brokentime = localtime(&result);
printf("%s", asctime(brokentime));
return(0);
}
程序输出如下:
Tue Aug 24 01:02:41 2010
如何仅从上面检索小时值,例如01?或者是否有其他系统调用可以获取系统当前小时数?我需要在此基础上采取行动
谢谢如果您希望它是一个数字(而不是字符串),那么只需访问
brokentime
结构中的相应字段即可:
time_t result;
result = time(NULL);
struct tm* brokentime = localtime(&result);
int h = brokentime->tm_hour; /* h now contains the hour (1) */
如果希望将其作为字符串,则必须自己格式化字符串(而不是使用asctime
):
使用
%I
而不是%H
获得12小时而不是24小时的时间 您应该使用tm.tm_hour作为小时值,以及其他值(分钟、秒、月等)Struct tm包含以下内容。上面的答案中没有一些信息,尽管它们完美地回答了OP
struct tm* brokentime = localtime(&result);
int hour = brokentime->tm_hour;
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
因此,您可以从此结构访问值。brokentime是指向结构的指针,而不是结构本身。
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