This repository has been archived by the owner on Oct 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Date.cpp
104 lines (88 loc) · 2.13 KB
/
Date.cpp
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
#include <regex>
#include "foo_musicbrainz.h"
#include "Date.h"
using namespace std::tr1;
using namespace pfc;
using namespace foo_musicbrainz;
#define STRING_TO_DATE_PART(part, index) \
if (matches[index].length() > 0) { \
part = atoi(matches[index].str().data()); \
} else { \
part = 0; \
}
Date::Date() {
year = month = day = 0;
}
Date::Date(short year, short month, short day) {
this->year = this->month = this->day = 0;
if (year == 0) return;
this->year = year;
if (month == 0) return;
this->month = month;
if (day == 0) return;
this->day = day;
}
Date::Date(string8 str) {
static regex rx("^\\s*(?:([12][0-9]{3})(?:-(?:([01]?[0-9])(?:-([0123]?[0-9])?)?)?)?)?\\s*$");
cmatch matches;
if (regex_search(str.get_ptr(), matches, rx)) {
STRING_TO_DATE_PART(year, 1)
STRING_TO_DATE_PART(month, 2)
STRING_TO_DATE_PART(day, 3)
} else {
year = month = day = 0;
}
}
#define COMPARE_DATE_PARTS(part) \
if (left.part != right.part) { \
if (left.part == 0) { \
return 1; \
} else if (right.part == 0) { \
return -1; \
} else { \
return left.part > right.part ? 1 : -1; \
} \
}
int Date::compare(const Date &left, const Date &right) {
COMPARE_DATE_PARTS(year)
COMPARE_DATE_PARTS(month)
COMPARE_DATE_PARTS(day)
return 0;
}
bool Date::operator>(const Date &other) const {
return compare(*this, other) == 1;
}
bool Date::operator<(const Date &other) const {
return compare(*this, other) == -1;
}
bool Date::operator>=(const Date &other) const {
return compare(*this, other) != -1;
}
bool Date::operator<=(const Date &other) const {
return compare(*this, other) != 1;
}
bool Date::operator==(const Date &other) const {
return compare(*this, other) == 0;
}
bool Date::operator!=(const Date &other) const {
return compare(*this, other) != 0;
}
Date::operator pfc::string8() const {
pfc::string8 str;
if (year != 0) str << year;
if (month != 0) {
str << "-";
if (month < 10) {
str << "0";
}
str << month;
}
if (day != 0) {
str << "-";
if (day < 10) {
str << "0";
}
str << day;
}
return str;
}