int date_add(int n, char *date_time)
{
char tmp[10] = {0};
int month_all[13];
int i;
int year, month, day;
// 闰年
int month_r[13] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 平年
int month_p[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (strlen(date_time) != 8)
return -1;
memcpy(tmp, date_time, 4);
year = atoi(tmp);
memset(tmp, 0x00, sizeof(tmp));
memcpy(tmp, date_time + 4, 2);
month = atoi(tmp);
memset(tmp, 0x00, sizeof(tmp));
memcpy(tmp, date_time + 6, 2);
day = atoi(tmp);
printf("year: %d month: %d day: %d\n", year, month, day);
if (((year % 4) == 0 && (year % 100) != 0) || (year % 400) == 0) // 闰年
{
printf("闰年!\n");
for (i = 0; i < 13; i++)
month_all[i] = month_r[i];
}
else //平年
{
for (i = 0; i < 13; i++)
month_all[i] = month_p[i];
}
day += n;
while (day > month_all[month])
{
day -= month_all[month];
month++;
while (month > 12)
{
month -= 12;
year++;
if (((year % 4) == 0 && (year % 100) != 0) || (year % 400) == 0) // 闰年
{
printf("闰年!\n");
for (i = 0; i < 13; i++)
month_all[i] = month_r[i];
}
else //平年
{
for (i = 0; i < 13; i++)
month_all[i] = month_p[i];
}
}
}
memset(date_time, 0x00, strlen(date_time));
sprintf(date_time, "%04d%02d%02d", year, month, day);
return 0;
}
int date_sub(int n, char *date_time)
{
char tmp[10] = {0};
int month_all[13];
int i;
int year, month, day;
// 闰年
int month_r[13] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 平年
int month_p[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (strlen(date_time) != 8)
return -1;
memcpy(tmp, date_time, 4);
year = atoi(tmp);
memset(tmp, 0x00, sizeof(tmp));
memcpy(tmp, date_time + 4, 2);
month = atoi(tmp);
memset(tmp, 0x00, sizeof(tmp));
memcpy(tmp, date_time + 6, 2);
day = atoi(tmp);
printf("year: %d month: %d day: %d\n", year, month, day);
if (((year % 4) == 0 && (year % 100) != 0) || (year % 400) == 0) // 闰年
{
printf("闰年!\n");
for (i = 0; i < 13; i++)
month_all[i] = month_r[i];
}
else //平年
{
for (i = 0; i < 13; i++)
month_all[i] = month_p[i];
}
day -= n;
while (day <= 0)
{
month--;
while (month <= 0)
{
month = 12 + month;
year--;
if (((year % 4) == 0 && (year % 100) != 0) || (year % 400) == 0) // 闰年
{
printf("闰年!\n");
for (i = 0; i < 13; i++)
month_all[i] = month_r[i];
}
else //平年
{
for (i = 0; i < 13; i++)
month_all[i] = month_p[i];
}
}
day = day + month_all[month];
}
memset(date_time, 0x00, strlen(date_time));
sprintf(date_time, "%04d%02d%02d", year, month, day);
return 0;
}
写了2个增加n天的函数,不知道对不对啊
[
本帖最后由 widon1104 于 2011-5-9 14:02 编辑 ]