Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract hours from time_t?

Tags:

c

time

time-t

I want to extract hours, minutes and seconds as integer values from a time_t value representing seconds since epoch.

The value for hours is not correct. Why?

#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);
    }
}

Output (the hour should be 10)

06:15:35
10:15:35

06:15:36
10:15:36

06:15:37
10:15:37
like image 599
Daniel Näslund Avatar asked Jun 28 '12 10:06

Daniel Näslund


2 Answers

int h = (t / 3600) % 24;  /* ### Your problem. */
like image 199
Adam Sznajder Avatar answered Sep 21 '22 09:09

Adam Sznajder


Your call to gmtime() already does it, the resulting struct tm has all the fields. See the documentation.

In other words, just

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

I would argue that this is the proper way, since it avoids involving scarily large numbers to do the conversion manually in your code. It does so in the best of ways, by making it Someone Else's Problem (i.e., abstracting it away). So fix your code not by adding the missing 0, but by using gmtime().

Also think about timezones.

like image 35
unwind Avatar answered Sep 19 '22 09:09

unwind