How to convert from UTC to local time in C?

前端 未结 10 1641
无人共我
无人共我 2020-12-05 20:44

It\'s a simple question, but the solution appears to be far from simple. I would like to know how to convert from UTC to local time. I am looking for a solution in C that\'s

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 21:19

    I followed the answer by @Dachschaden and I made an example which also shows human-readable output and I remove the DST option for the difference in seconds between UTC and local time. Here it is:

    #include 
    #include 
    
    #define DATE_MAX_STR_SIZE 26
    #define DATE_FMT "%FT%TZ%z"
    
    int main() {
    
        time_t now_time, now_time_local;
        struct tm now_tm_utc, now_tm_local;
        char str_utc[DATE_MAX_STR_SIZE];
        char str_local[DATE_MAX_STR_SIZE];
    
        time(&now_time);
        gmtime_r(&now_time, &now_tm_utc);
        localtime_r(&now_time, &now_tm_local);
    
        /* human readable */
        strftime(str_utc, DATE_MAX_STR_SIZE, DATE_FMT, &now_tm_utc);
        strftime(str_local, DATE_MAX_STR_SIZE, DATE_FMT, &now_tm_local);
    
        printf("\nUTC: %s", str_utc);
        printf("\nLOCAL: %s\n", str_local);
    
        /* seconds (epoch) */
        /* let's forget about DST for time difference calculation */
        now_tm_local.tm_isdst = 0;
        now_tm_utc.tm_isdst = 0;
        now_time_local = now_time + (mktime(&now_tm_local) - mktime(&now_tm_utc));
    
        printf("\nUTC in seconds: %lu", now_time);
        printf("\nLOCAL in seconds: %lu\n", now_time_local);
    
        return 0;
    }
    

    Output on my machine is:

    UTC: 2016-05-05T15:39:11Z-0500
    LOCAL: 2016-05-05T11:39:11Z-0400
    
    UTC in seconds: 1462462751
    LOCAL in seconds: 1462448351
    

    Note that DST is on in this case (there's a 1 hour time zone offset difference between UTC and LOCAL).

提交回复
热议问题