自定义的时间格式,与C语言中的struct tm有点区别。此代码仅供参考。如果发现代码中的错误,请留言或是给我电子邮件,不胜感谢!
- /*
- * 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 <stdio.h>
- 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;
- }