/*******************************************************
//function: today subtract one day c language implement
//filename:sub_one_day.c
//tools:vc++6.0
//anthor:chinayaosir QQ:44633197
//date :09/06/2011
//blog :http://blog.csdn.net/chinayaosir
//note :禁止其它网站转载此文章
*******************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <time.h>
//闰年判断函数
int isleap(int year){
if ((year%4==0)&&(year%100!=0)||(year%400==0))
return 0;
else
return 1;
}
//当前日期减少一天的函数
void subtractoneday (char indate[10],char outdate[10]){
//定义变量
int mm,dd,yyyy;
char temp2[2],temp4[5];
int year,month,day;
//get mm/dd/yyyy from indate[mm/dd/yy]
strncpy(temp2,indate,2);
mm=atoi(temp2);
strncpy(temp2,indate+3,2);
dd=atoi(temp2);
strcpy(temp4,"20");
strncat(temp4,indate+6,2);
yyyy=atoi(temp4);
//日期减1天的C算法实现
if(mm==1 && dd==1){
year =yyyy - 1;
month =12;
day =31;
}else if(mm==3 && dd==1){
if (isleap(yyyy)==0){day=29;} else {day=28;}
year =yyyy;
month =mm - 1;
}else if((mm==2||mm==4||mm==6||mm==8||mm==9||mm==11) && (dd==1)){
year =yyyy;
month =mm - 1;
day =31;
}else if((mm==5||mm==7||mm==10||mm==12) && (dd==1)){
year =yyyy;
month =mm - 1;
day =30;
}else if (dd>1){
year =yyyy;
month =mm;
day =dd - 1;
}
//组装日期字符串
itoa(year,temp4,10);
strcpy(outdate,temp4);
strcat(outdate,"/");
itoa(month,temp2,10);
strcat(outdate,temp2);
strcat(outdate,"/");
itoa(day,temp2,10);
strcat(outdate,temp2);
}
int main(){
char today[10]="09/04/11";
char yesterday[10];
//_strdate(today);
printf("today=%s\n",today);
subtractoneday(today,yesterday);
printf("yesterday=%s\n",yesterday);
return 0;
}
运行结果如下:
today=09/04/11
yesterday=2011/9/3