數(shù)據(jù)結構算法:日期加減算法

字號:

原定于2008年11月全國計算機軟件資格考試推遲,改為2008年12月21日,大家復習好沒!考試大整理了2008年下半年全國計算機軟件資格考試考前程序員數(shù)據(jù)結構算法知識,希望對各位有所幫助,考試大和各位一起學習!希望各位能夠順利通過2008年下半年全國計算機軟件資格考試!
    自定義的時間格式,與C語言中的struct tm有點區(qū)別。此代碼僅供參考。
    /*
    * Already be tested in linux with gcc 4.1.2.
    * Already be tested in windows with VC2005.
    * Please contact me with any bugs in these two functions.
    * email: ka-bar_strider@hotmail.com
    * ka-bar, 2008-12-16
    */
    #include
    typedef struct tagdate
    {
    int year;
    int mon;
    int day;
    int hour;
    int min;
    int sec;
    }mathdate,*mathdateptr;
    void date_add(mathdateptr orig_date, int days)
    {
    int monthdays[2][13] = {{0,31,28,31,30,31,30,31,31,30,31,30,31},
    {0,31,29,31,30,31,30,31,31,30,31,30,31}};
    for ( ; ; orig_date->mon = 1, orig_date->year++) //for year
    {
    int leapyear = orig_date->year%4 == 0 ? 1:0;
    for ( ; ; orig_date->mon++) //for month
    {
    int cur_mon_days = monthdays[leapyear][orig_date->mon];
    if ((days -= (cur_mon_days - orig_date->day)) > 0)
    {
    orig_date->day = 0;
    if (orig_date->mon >= 12)
    break;
    }
    else
    {
    orig_date->day = cur_mon_days + days;
    return;
    }
    }//end for month
    }//end for year
    }
    void date_sub(mathdateptr orig_date, int days)
    {
    int monthdays[2][13] = {{0,31,28,31,30,31,30,31,31,30,31,30,31},
    {0,31,29,31,30,31,30,31,31,30,31,30,31}};
    do
    {
    if ((days -= orig_date->day) <= 0)
    {
    orig_date->day = 0 - days;
    return;
    }
    else
    {
    int leapyear = 0;
    if (--orig_date->mon < 1)
    {
    orig_date->year--;
    orig_date->mon = 12;
    leapyear = orig_date->year%4 == 0 ? 1:0;
    }
    orig_date->day = monthdays[leapyear][orig_date->mon];
    }
    } while(1);// month
    }
    int main()
    {
    mathdate orig_date = {2007,1,26,0,0,0};
    printf("%04d%02d%02d-%02d:%02d:%02d\n",
    orig_date.year,orig_date.mon,orig_date.day,orig_date.hour,orig_date.min,orig_date.sec);
    date_sub(&orig_date,712);
    printf("%04d%02d%02d-%02d:%02d:%02d\n",
    orig_date.year,orig_date.mon,orig_date.day,orig_date.hour,orig_date.min,orig_date.sec);
    date_add(&orig_date,712);
    printf("%04d%02d%02d-%02d:%02d:%02d\n",
    orig_date.year,orig_date.mon,orig_date.day,orig_date.hour,orig_date.min,orig_date.sec);
    getchar();
    return 0;
    }