1. 程式人生 > >C++ 計算任意兩個日期之間的天數

C++ 計算任意兩個日期之間的天數

gpo start plain efault ediff include win sel put

C++寫的一個計算兩個日期之間天數的小程序:

[cpp] view plain copy
  1. #include <Windows.h>
  2. #include <stdio.h>
  3. struct tagDate
  4. {
  5. int year;
  6. int month;
  7. int day;
  8. };
  9. //設置日期
  10. void SetDate(int y, int m, int d, tagDate *date)
  11. {
  12. date->year = y;
  13. date->month = m;
  14. date->day = d;
  15. }
  16. //是否閏年
  17. int IsLeapYear(int year)
  18. {
  19. return ((year%4==0) && (year%100!=0)||year%400==0);
  20. }
  21. //得到date.month的最大天數
  22. int GetLastDay(tagDate date)
  23. {
  24. int num;
  25. switch(date.month)
  26. {
  27. case 1:
  28. case 3:
  29. case 5:
  30. case 7:
  31. case 8:
  32. case 10:
  33. case 12:
  34. num=31;
  35. break;
  36. case 2:
  37. num = 28+IsLeapYear(date.year);
  38. break;
  39. default:
  40. num = 30;
  41. }
  42. return num;
  43. }
  44. //日期是否合法
  45. int IsDateValid(tagDate date)
  46. {
  47. if(date.year <0 || date.month <1 || date.month> 12)
  48. return 0;
  49. if(date.day <1 || date.day> GetLastDay(date))
  50. return 0;
  51. return 1;
  52. }
  53. //date+1
  54. void AddDay(tagDate *date)
  55. {
  56. date->day++;
  57. if(date->day > GetLastDay(*date))
  58. {
  59. date->day = 1;
  60. date->month++;
  61. if(date->month > 12)
  62. {
  63. date->month = 1;
  64. date->year++;
  65. }
  66. }
  67. }
  68. //date1比date2小返回值為1,否則為0
  69. int Compare(tagDate date1, tagDate date2)
  70. {
  71. if(date1.year < date2.year)
  72. return 1;
  73. if(date1.year <= date2.year && date1.month < date2.month)
  74. return 1;
  75. if(date1.year <= date2.year && date1.month <= date2.month && date1.day < date2.day)
  76. return 1;
  77. return 0;
  78. }
  79. //計算兩個日期的間隔天數
  80. long DateDiff(tagDate date1, tagDate date2)
  81. {
  82. long delta = 0;
  83. tagDate date3;
  84. //若date1 > date2,交換date1,date2
  85. if(!Compare(date1, date2))
  86. {
  87. date3 = date2;
  88. date2 = date1;
  89. date1 = date3;
  90. }
  91. //date1比date2少時,date1日期加1
  92. while(Compare(date1,date2))
  93. {
  94. AddDay(&date1);
  95. delta++;
  96. }
  97. return delta;
  98. }
  99. void main()
  100. {
  101. tagDate date1, date2;
  102. int y, m, d;
  103. system("cls");
  104. while(1)
  105. {
  106. puts("\nInput date1\t ");
  107. scanf("%d,%d,%d", &y, &m, &d);
  108. SetDate(y, m, d, &date1);
  109. if(!IsDateValid(date1))
  110. {
  111. puts( "date1 is invalid !");
  112. exit(1);
  113. }
  114. puts("\nInput date2\t ");
  115. scanf("%d,%d,%d", &y, &m, &d);
  116. SetDate(y, m, d, &date2);
  117. if(!IsDateValid(date2))
  118. {
  119. puts( "date2 is invalid !");
  120. exit(1);
  121. }
  122. //
  123. printf("\nResult : [%ld]", DateDiff(date1,date2));
  124. }
  125. }

https://blog.csdn.net/hellokandy/article/details/52194332

C++ 計算任意兩個日期之間的天數