您可以提取年、月和日,然后根据每个月的天数和闰年添加您的天数。
#include <stdio.h>
unsigned long AddDays(unsigned long StartDay, unsigned long Days)
{
unsigned long year = StartDay / 10000, month = StartDay / 100 % 100 - 1, day = StartDay % 100 - 1;
while (Days)
{
unsigned daysInMonth[2][12] =
{
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, // 365 days, non-leap
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } // 366 days, leap
};
int leap = !(year % 4) && (year % 100 || !(year % 400));
unsigned daysLeftInMonth = daysInMonth[leap][month] - day;
if (Days >= daysLeftInMonth)
{
day = 0;
Days -= daysLeftInMonth;
if (++month >= 12)
{
month = 0;
year++;
}
}
else
{
day += Days;
Days = 0;
}
}
return year * 10000 + (month + 1) * 100 + day + 1;
}
int main(void)
{
unsigned long testData[][2] =
{
{ 20130228, 0 },
{ 20130228, 1 },
{ 20130228, 30 },
{ 20130228, 31 },
{ 20130228, 32 },
{ 20130228, 365 },
{ 20130228, 366 },
{ 20130228, 367 },
{ 20130228, 365*3 },
{ 20130228, 365*3+1 },
{ 20130228, 365*3+2 },
};
unsigned i;
for (i = 0; i < sizeof(testData) / sizeof(testData[0]); i++)
printf("%lu + %lu = %lu\n", testData[i][0], testData[i][1], AddDays(testData[i][0], testData[i][1]));
return 0;
}
输出(ideone):
20130228 + 0 = 20130228
20130228 + 1 = 20130301
20130228 + 30 = 20130330
20130228 + 31 = 20130331
20130228 + 32 = 20130401
20130228 + 365 = 20140228
20130228 + 366 = 20140301
20130228 + 367 = 20140302
20130228 + 1095 = 20160228
20130228 + 1096 = 20160229
20130228 + 1097 = 20160301
另一种选择是提取年、月和日,并使用 mktime() 或类似函数将它们转换为自 epoch 以来的秒数,将代表那些天的秒数添加到该秒数给定日期,然后使用gmtime() 或localtime() 或类似函数将生成的秒数转换回日期,然后构造长整数值。我选择不使用这些功能来避免时区和夏令时之类的事情。我想要一个简单且包含的解决方案。