tags:

views:

66

answers:

4

Hi,

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 currect hour of the system can be obtained ? I need to take an action based on this.

Thanks

+2  A: 

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.

Tyler McHenry
brokentime is a pointer to a structure, not a struct itself.
James Curran
@James thanks for point that out. Fixed.
Tyler McHenry
+5  A: 
struct tm* brokentime = localtime(&result); 
int hour = brokentime->tm_hour;
James Curran
+1  A: 

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

Nickolay O.
A: 

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.

Praveen S