fork download
  1. #include <stdio.h>
  2.  
  3. unsigned long AddDays(unsigned long StartDay, unsigned long Days)
  4. {
  5. unsigned long year = StartDay / 10000, month = StartDay / 100 % 100 - 1, day = StartDay % 100 - 1;
  6.  
  7. while (Days)
  8. {
  9. unsigned daysInMonth[2][12] =
  10. {
  11. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, // 365 days, non-leap
  12. { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } // 366 days, leap
  13. };
  14.  
  15. int leap = !(year % 4) && (year % 100 || !(year % 400));
  16.  
  17. unsigned daysLeftInMonth = daysInMonth[leap][month] - day;
  18.  
  19. if (Days >= daysLeftInMonth)
  20. {
  21. day = 0;
  22. Days -= daysLeftInMonth;
  23. if (++month >= 12)
  24. {
  25. month = 0;
  26. year++;
  27. }
  28. }
  29. else
  30. {
  31. day += Days;
  32. Days = 0;
  33. }
  34. }
  35.  
  36. return year * 10000 + (month + 1) * 100 + day + 1;
  37. }
  38.  
  39. int main(void)
  40. {
  41. unsigned long testData[][2] =
  42. {
  43. { 20130228, 0 },
  44. { 20130228, 1 },
  45. { 20130228, 30 },
  46. { 20130228, 31 },
  47. { 20130228, 32 },
  48. { 20130228, 365 },
  49. { 20130228, 366 },
  50. { 20130228, 367 },
  51. { 20130228, 365*3 },
  52. { 20130228, 365*3+1 },
  53. { 20130228, 365*3+2 },
  54. };
  55.  
  56. unsigned i;
  57.  
  58. for (i = 0; i < sizeof(testData) / sizeof(testData[0]); i++)
  59. printf("%lu + %lu = %lu\n", testData[i][0], testData[i][1], AddDays(testData[i][0], testData[i][1]));
  60.  
  61. return 0;
  62. }
  63.  
  64.  
Success #stdin #stdout 0s 1832KB
stdin
Standard input is empty
stdout
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