Friday, November 30, 2012

Ref: How to convert from UTC to local time in C?

Reference: How to convert from UTC to local time in C?

I think the following from stackoverflow is the best portable solution if timegm() is not in the system.

#include <stdio.h>
#include <time.h>
#include <assert.h>

time_t my_timegm(struct tm *tm) {
    time_t epoch = 0;
    time_t offset = mktime(gmtime(&epoch));
    time_t utc = mktime(tm);
    return difftime(utc, offset);
}


int main(void) {
    time_t now = time(0);
    struct tm local = *localtime(&now);
    struct tm utc = *gmtime(&now);
    time_t t1 = mktime(&local);
    time_t t2 = my_timegm(&utc);
    assert(t1 == t2);
    printf("t =%lu\nt1=%lu\nt2=%lu\n",now,t1,t2);
    return 0;
}

No comments: