因為系統時間與實際時間不一樣,程式目的為將系統時間校正至真實時間:
已知系統時間的起始點stime0 與對應的真實時間stime1,給定某個系統時間dtime0,程式,將之轉換為真實時間dtime1
應該有更好的方法,但目前就是直接算stime0與dtime0的差距,再加到stime1;即dtime1=stime1+(dtime0-stime0)
原本以為半天可以做完,最後花了整整兩天... 就為了考慮所有狀況..,測試過是沒問題,還是有小部份可以精簡的地方,但是懶的改了.
#include
#include
typedef struct OBSTIME{
int yr;
int mon;
int day;
int hr;
int min;
int sec;
}obstime;
void add_time();
void cmptime(obstime *t1,obstime *t2);
int julian_cnt(int yr,int mon,int day);
//Global variable
obstime stime0={1,1,1,3,0,0};//system start time : dummy
obstime stime1={2012,12,15,14,53,40}; //system start time : true
obstime dtime0; //data time : dummy
obstime dtime1; //data time : ture
int day_lyr[12]={31,29,31,30,31,30,31,31,30,31,30,31}; //leap year day array
int day_cyr[12]={31,28,31,30,31,30,31,31,30,31,30,31}; //common year day array
int del_sec;//delta seconds
int del_day;//delta days
void add_time(){
int *day_yr; //ptr to day arry of the year
cmptime(&stime0,&dtime0); //compute delta time in second & day
dtime1.sec=stime1.sec+del_sec; //add seconds
dtime1.min=stime1.min+(dtime1.sec/60);
dtime1.sec=dtime1.sec%60; //sec. ok
dtime1.hr=stime1.hr+(dtime1.min/60);
dtime1.min=dtime1.min%60;//min. ok
dtime1.day=stime1.day+(dtime1.hr/24);
dtime1.hr=dtime1.hr%24;//hr. ok
dtime1.day+=del_day; //add days
dtime1.mon=stime1.mon;
dtime1.yr=stime1.yr;
if((stime1.yr%4==0 && stime1.yr%100!=0) || stime1.yr%400==0){ //leap year
day_yr=day_lyr;
}
else{ //common year
day_yr=day_cyr;
}
while((dtime1.day-day_yr[dtime1.mon-1])>0){
dtime1.day=dtime1.day-day_yr[dtime1.mon-1];
dtime1.mon=dtime1.mon+1;
if(dtime1.mon==13){
dtime1.mon=1;
dtime1.yr++;
if((dtime1.yr%4==0 && dtime1.yr%100!=0) || dtime1.yr%400==0){ //leap year
day_yr=day_lyr;
}
else{ //common year
day_yr=day_cyr;
}
}
}
}
void cmptime(obstime *t1,obstime *t2){
int jday1,jday2;
int sec1,sec2;
int yr=t2->yr;
int lday=366,cday=365;
jday1=julian_cnt(t1->yr,t1->mon,t1->day);
jday2=julian_cnt(t2->yr,t2->mon,t2->day);
while(yr>t1->yr){//over the year or futher..
yr--;
if((yr%4==0 && yr%100!=0) || yr%400==0){ //leap year
jday2=jday2+366;
}
else{ //common year
jday2=jday2+365;
}
}
sec1=t1->hr*3600+t1->min*60+t1->sec;
sec2=t2->hr*3600+t2->min*60+t2->sec;
if(sec2>=sec1){
del_sec=sec2-sec1;
del_day=jday2-jday1;
}
else{
del_sec=sec2-sec1+86400;
del_day=jday2-jday1-1;
}
//printf("del_day=%d",del_day);
//system("PAUSE");
//printf("del_sec=%d",del_sec);
//system("PAUSE");
}
int julian_cnt(int yr,int mon,int day){
int jday=0;
int *day_yr;
int i=0;
if((yr%4==0 && yr%100!=0) || yr%400==0){ //leap year
day_yr=day_lyr;
}
else{ //common year
day_yr=day_cyr;
}
while(i+1 != mon){
jday=jday+day_yr[i];
i++;
}
jday=jday+day;
return jday;
}