How to extract a clock from time_t?

I want to extract hours, minutes, and seconds as integer values ​​from a time_t value representing seconds from an era.

The value for several hours is incorrect. What for?

#include <stdio.h> #include <time.h> #include <unistd.h> int main() { char buf[64]; while (1) { time_t t = time(NULL); struct tm *tmp = gmtime(&t); int h = (t / 360) % 24; /* ### My problem. */ int m = (t / 60) % 60; int s = t % 60; printf("%02d:%02d:%02d\n", h, m, s); /* For reference, extracts the correct values. */ strftime(buf, sizeof(buf), "%H:%M:%S\n", tmp); puts(buf); sleep(1); } } 

Exit (hour should be 10)

 06:15:35 10:15:35 06:15:36 10:15:36 06:15:37 10:15:37 
+6
source share
2 answers

Your call to gmtime() already does, the result is struct tm all fields. See the documentation .

In other words, just

 printf("hours is %d\n", tmp->tm_hour); 

I would say that this is the right way, since it avoids significant numbers in order to do the conversion manually in your code. He does this in the best way, creating his “Alien Problem” (that is, abstracting him). Therefore, correct your code by not adding the missing 0 , but using gmtime() .

Also think about time zones.

+5
source
 int h = (t / 3600) % 24; /* ### Your problem. */ 
+11
source

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


All Articles