How to convert from UTC to local time in C?

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

    //working stand alone function adjusting UTC to local date and time
    //globals(unsigned integers): gps.Mth, gps.Yr, gps.Hm (eg:2115 for 21:15)
    //adjust date and time according to UTC
    //tz(timezone) eg: 1100, for 11 hours, tzdir: 1 forward, 0 backwards            
    
    
    
    
    
        void AdjustUTCToTimeZone(u16 tz, u8 tzdir){
        u8 maxDayInAnyMonth[13] = {0,31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; //gps.Mth 1-12 (not zero)
            if(gps.Yr%4==0){maxDayInAnyMonth[2]=29;}//adjust for leapyear
            u8 maxDayUtcMth =maxDayInAnyMonth[gps.Mth];
            u8 maxDayPrevMth=maxDayInAnyMonth[gps.Mth-1];
            if(!maxDayPrevMth){maxDayPrevMth=31;} //month before utc month
    
            u16 hr=(gps.Hm/100)*100;u16 m=gps.Hm-hr;  //2115 --> 2100 hr and 15 min
            if(tzdir){//adjusting forwards
                tz+=gps.Hm;
                if(tz>2400){gps.Hm=tz-2400;gps.Day++;                //spill over to next day
                      if(gps.Day>maxDayUtcMth){ gps.Day=1;gps.Mth++; //spill over to next month
                          if(gps.Mth>12){gps.Mth=1; gps.Yr++;        //spill over to next year
                          }
                      }
                }else{gps.Hm=tz;}
            }else{//adjusting backwards
                if(tz>gps.Hm){gps.Hm=(2400-(tz-hr))+m;gps.Day--;  // back to previous day
                      if(gps.Day==0){                             //back to previous month
                         gps.Mth--;gps.Day=maxDayPrevMth;
                         if(!gps.Mth){gps.Mth=12;                 //back to previous year
                            gps.Yr--;
                         }
                      }
                }else{gps.Hm-=tz;}
            }
        }
    

提交回复
热议问题