How to get hour value from current time in unix (using C)

I have the following program to get the 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 program output is as follows:

Tue Aug 24 01:02:41 2010

How to get only the hour value indicated 01 from the above?
Or is there any other system call where an hour of system operation can be obtained? I need to take action based on this.

thank

+3
source share
4 answers

If you want this number (not a string), just enter the corresponding field in the 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 to be like a string, you will have to format the string yourself (instead of 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") */

%I %H, 12- 24- .

+2
struct tm* brokentime = localtime(&result); 
int hour = brokentime->tm_hour;
+5

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

+1
source

The tm structure consists of the following. Some of the information is missing from the answers above, although they answer 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

This way you can access the values ​​from this structure.

0
source

Source: https://habr.com/ru/post/1761165/


All Articles