How to convert from UTC to local time in C?

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

    A simple and effective way: Add (or subtract) the number of seconds between your time zone and UTC (considering daylight saving time).

    As an example that worked just fine a minute ago, on December 30, 2017, with U.S. Mountain Standard Time (no DST), which is 7 hours behind UTC:

    time_t     current_time_UTC;
    time_t     current_time_MST;
    
    struct tm *current_broken_time_MST;
    
    uint32_t seven_hours_in_seconds = 25200; // Get this any way you want
    
    current_time_UTC = time (NULL);                                 // UTC
    current_time_MST = current_time_UTC - seven_hours_in_seconds;   // MST
    
    current_broken_time_MST = localtime (¤t_time_MST);        // MST
    

    Enjoy.

提交回复
热议问题