-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdate.cpp
96 lines (77 loc) · 2.75 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
struct Date {
int day;
int month;
int year;
const int kDaysInMonth[13] = {-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int getDaysInMonth() { return kDaysInMonth[month] + (month == 2 && leap(year)); }
bool leap(int year) { return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)); }
int countDays() {
int res = 0;
for (int i = 1970; i < year; i++)
res += 365 + leap(i);
for (int i = 1; i < month; i++)
res += kDaysInMonth[i] + (i == 2 && leap(year));
res += day;
return res;
}
bool valid() { return (day <= getDaysInMonth()) && (this -> countDays() >= 0); }
void printRaw(int format) {
if (format == 0)
cout << year << "-" << (month < 10 ? "0" : "") << month << "-" << (day < 10 ? "0" : "") << day;
else if (format == 1)
cout << (month < 10 ? "0" : "") << month << "-" << (day < 10 ? "0" : "") << day << "-" << year;
else if (format == 2)
cout << (day < 10 ? "0" : "") << day << "-" << (month < 10 ? "0" : "") << month << "-" << year;
cout << endl;
}
Date(int d, int m, int y): day(d), month(m), year(y) {}
/**
* format = 0: YYYY-MM-DD
* format = 1: MM-DD-YYYY
* format = 2: DD-MM-YYYY
* returns {DD, MM, YYYY}
**/
Date(string dateRaw, unsigned int format) {
int p = 0;
if (format == 0) {
year = (dateRaw[p] - '0') * 1000 + (dateRaw[p + 1] - '0') * 100 +
(dateRaw[p + 2] - '0') * 10 + (dateRaw[p + 3] - '0');
p = 5;
}
rep(z, 0, 2) {
int v = (dateRaw[p] - '0') * 10 + (dateRaw[p + 1] - '0');
if (z)
day = v;
else
month = v;
p += 3;
}
if (format > 0) {
if (format == 2)
swap(day, month);
year = (dateRaw[p] - '0') * 1000 + (dateRaw[p + 1] - '0') * 100 +
(dateRaw[p + 2] - '0') * 10 + (dateRaw[p + 3] - '0');
}
}
bool operator==(const Date& other) { return tie(day, month, year) == tie(other.day, other.month, other.year); }
bool operator!=(const Date& other) { return !((*this) == other); }
bool operator<(const Date& other) { return this -> countDays() < other.countDays(); }
bool operator>(const Date& other) { return other < (*this); }
void operator++() {
int daysMax = getDaysInMonth();
day++;
if (day > daysMax) {
day = 1;
month++;
if (month == 13) {
month = 1;
year++;
}
}
}
void operator++(int) {
Date temp = *this;
this -> operator++();
return temp;
}
};