/src/muduo/muduo/base/Date.cc
Line | Count | Source |
1 | | // Use of this source code is governed by a BSD-style license |
2 | | // that can be found in the License file. |
3 | | // |
4 | | // Author: Shuo Chen (chenshuo at chenshuo dot com) |
5 | | |
6 | | #include "muduo/base/Date.h" |
7 | | #include <stdio.h> // snprintf |
8 | | #include <time.h> // struct tm |
9 | | |
10 | | namespace muduo |
11 | | { |
12 | | namespace detail |
13 | | { |
14 | | |
15 | | char require_32_bit_integer_at_least[sizeof(int) >= sizeof(int32_t) ? 1 : -1]; |
16 | | |
17 | | // algorithm and explanation see: |
18 | | // http://www.faqs.org/faqs/calendars/faq/part2/ |
19 | | // http://blog.csdn.net/Solstice |
20 | | |
21 | | int getJulianDayNumber(int year, int month, int day) |
22 | 2 | { |
23 | 2 | (void) require_32_bit_integer_at_least; // no warning please |
24 | 2 | int a = (14 - month) / 12; |
25 | 2 | int y = year + 4800 - a; |
26 | 2 | int m = month + 12 * a - 3; |
27 | 2 | return day + (153*m + 2) / 5 + y*365 + y/4 - y/100 + y/400 - 32045; |
28 | 2 | } |
29 | | |
30 | | struct Date::YearMonthDay getYearMonthDay(int julianDayNumber) |
31 | 0 | { |
32 | 0 | int a = julianDayNumber + 32044; |
33 | 0 | int b = (4 * a + 3) / 146097; |
34 | 0 | int c = a - ((b * 146097) / 4); |
35 | 0 | int d = (4 * c + 3) / 1461; |
36 | 0 | int e = c - ((1461 * d) / 4); |
37 | 0 | int m = (5 * e + 2) / 153; |
38 | 0 | Date::YearMonthDay ymd; |
39 | 0 | ymd.day = e - ((153 * m + 2) / 5) + 1; |
40 | 0 | ymd.month = m + 3 - 12 * (m / 10); |
41 | 0 | ymd.year = b * 100 + d - 4800 + (m / 10); |
42 | 0 | return ymd; |
43 | 0 | } |
44 | | } // namespace detail |
45 | | const int Date::kJulianDayOf1970_01_01 = detail::getJulianDayNumber(1970, 1, 1); |
46 | | } // namespace muduo |
47 | | |
48 | | using namespace muduo; |
49 | | using namespace muduo::detail; |
50 | | |
51 | | Date::Date(int y, int m, int d) |
52 | 0 | : julianDayNumber_(getJulianDayNumber(y, m, d)) |
53 | 0 | { |
54 | 0 | } |
55 | | |
56 | | Date::Date(const struct tm& t) |
57 | 0 | : julianDayNumber_(getJulianDayNumber( |
58 | 0 | t.tm_year+1900, |
59 | 0 | t.tm_mon+1, |
60 | 0 | t.tm_mday)) |
61 | 0 | { |
62 | 0 | } |
63 | | |
64 | | string Date::toIsoString() const |
65 | 0 | { |
66 | 0 | char buf[32]; |
67 | 0 | YearMonthDay ymd(yearMonthDay()); |
68 | 0 | snprintf(buf, sizeof buf, "%4d-%02d-%02d", ymd.year, ymd.month, ymd.day); |
69 | 0 | return buf; |
70 | 0 | } |
71 | | |
72 | | Date::YearMonthDay Date::yearMonthDay() const |
73 | 0 | { |
74 | 0 | return getYearMonthDay(julianDayNumber_); |
75 | 0 | } |
76 | | |