计算两个日期之间的天数

普通写法

不使用算法, 直接写一个普通的出来.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <iostream>
using namespace std;

class Date {
int year;
int month;
int day;

public:
Date(const int year, const int month, const int day): year(year), month(month), day(day) {};

Date() {
year = 0;
month = 0;
day = 0;
}

int getDateNumber() const {
return year * 10000 + month * 100 + day;
}

int getMonthDays() const {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 2:
break;
default:
return 30;
}
// 否则就是2月份
if (isLunar()) {
return 29;
}
return 28;
}

bool operator>(const Date& another) const {
return getDateNumber() > another.getDateNumber();
}

bool operator<(const Date& another) const {
return getDateNumber() < another.getDateNumber();
}

bool operator==(const Date& another) const {
return getDateNumber() == another.getDateNumber();
}

Date& operator++() {
// 日期自增操作
day++;
if (day > getMonthDays()) {
day = 1;
month++;
if (month > 12) {
month = 1;
year++;
}
}
return *this;
}

// 判断是否为闰年
bool isLunar() const {
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}

// 获取两个日期之间的天数
friend int getDaysBetweenDates(Date& date1, Date& date2);
};

int getDaysBetweenDates(Date& date1, Date& date2) {
// 判断两个日期的大小 保证date1 先于 date2
if (date1 > date2) {
// 交换
const Date tempDate = date1;
date1 = date2;
date2 = tempDate;
}

// 用自增实现判断
int counter = 0;
while (date1 < date2) {
counter++;
++date1;
}

// 返回结果
return counter;
}


int main() {
Date d1(2006, 2, 21);
Date d2(2006, 10, 16);
cout << getDaysBetweenDates(d1, d2) << endl;
return 0;
}

对应的输出如下:

1
237

由此可见, 这样的写法虽然很简单, 但是内容还是挺多的, 比较的浪费时间. 那么有没有 更简单, 更快速 的方法呢?

最简代码

直接上代码以及示例, 具体原理不作介绍.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

// 计算从头开始, 到指定日期的起始天数
int countDays(int y, int m, const int d) {
if (m < 3) y--, m += 12;
return 365 * y + (y >> 2) - y / 100 + y / 400 + (153 * m - 457) / 5 + d - 306;
}


int main() {
// 则可以直接通过这个函数计算天数差
int daysBetween = abs(countDays(2006, 2, 21) - countDays(2006, 10, 16));
cout << "天数差为" << daysBetween << endl;
return 0;
}

输出为:

1
天数差为237