开发者

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 ?

Or is there any other system call where the 开发者_如何学Ccurrect 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:

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):

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.


You should use tm.tm_hour for the hour value, as well, as other ones (minutes, seconds, month, etc)


Struct tm consists of the following. Some information is not present in the answers above, though they answer the OP perfectly.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜