How to convert from UTC to local time in C?

前端 未结 10 1638
无人共我
无人共我 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:27

    Ahm ... I might just be a beginner in C, but I got this working example:

    #include 
    #include 
    int main(void)
    {
            time_t abs_ts,loc_ts,gmt_ts;
            struct tm loc_time_info,gmt_time_info;
    
            /*Absolute time stamp.*/
            time(&abs_ts);
    
            /*Now get once the local time for this time stamp,
            **and once the GMT (UTC without summer time) time stamp.*/
            localtime_r(&abs_ts,&loc_time_info);
            gmtime_r(&abs_ts,&gmt_time_info);
    
            /*Convert them back.*/
            loc_ts=mktime(&loc_time_info);
            gmt_ts=mktime(&gmt_time_info);
    
            /*Unfortunately, GMT still has summer time. Get rid of it:*/
            if(gmt_time_info.tm_isdst==1)
                    {gmt_ts-=3600;}
    
            printf("Local timestamp: %lu\n"
                    "UTC timestamp: %lu\n"
                    "Difference in hours: %lu\n\n",
                    loc_ts,
                    gmt_ts,
                    (loc_ts-gmt_ts)/3600);
    
            return 0;
    }
    

    Which produces this output:

    Local timestamp: 1412554119

    GMT timestamp: 1412546919

    Difference in hours: 2

    Now you have the difference between UTC and local time in seconds. That should be enough to convert it.

    One note to your code, aseq: you are using malloc without need here (you can memset values on the stack as well, and malloc can be expensive while stack allocation is often much faster), and you do not free it. That's very, very bad practise.

    Another thing:

    memset(tp, 0, sizeof(struct tm));

    Would be better done if you'd pass sizeof(*tp) (or, if you put tp on the stack, sizeof(tp)) to memset. That ensures that even if the type of your object changes, it will still be fully memset.

提交回复
热议问题