12 inline bool is_leap_year(int32_t y)
13 { return y%4==0 && (y%100 || y%400==0); }
15 inline uint8_t month_days(int32_t y, uint8_t m)
25 return is_leap_year(y)?29:28;
32 inline int cmp_(T a, T b)
49 DateTime::DateTime(const TimeStamp &ts):
61 DateTime::DateTime(int32_t y, uint8_t m, uint8_t d):
71 void DateTime::add_days(int32_t days)
73 unsigned new_year=year;
75 /* Leap years have a 400 year cycle, so any 400 consecutive years have a
76 constant number of days */
77 new_year+=days/146097*400;
86 // Fudge factor for leap day
87 int fudge=(month<=2)?1:0;
89 // (Almost) every 4 year cycle has 1 leap year and 3 normal years
90 unsigned cycles=days/1461;
95 // See how many non-leap-years we counted as leap years and reclaim the lost days
96 unsigned missed_leap_days=((year-fudge)%100+cycles*4)/100;
97 if((year-fudge)%400+cycles*4>=400)
100 days+=missed_leap_days;
102 // Count single years from the 4 year cycle
108 if((year-fudge)%4+cycles>=4)
110 // We passed a leap year - decrement days
114 days=is_leap_year(new_year)?365:364;
123 while(mday+days>month_days(year, month))
125 days-=month_days(year, month);
137 DateTime DateTime::operator+(const TimeDelta &td) const
140 dt.add_raw(td.raw());
144 DateTime &DateTime::operator+=(const TimeDelta &td)
150 int DateTime::cmp(const DateTime &dt) const
152 if(int c=cmp_(year, dt.year))
154 if(int c=cmp_(month, dt.month))
156 if(int c=cmp_(mday, dt.mday))
158 if(int c=cmp_(hour, dt.hour))
160 if(int c=cmp_(minute, dt.minute))
162 if(int c=cmp_(second, dt.second))
164 if(int c=cmp_(usec, dt.usec))
169 TimeStamp DateTime::get_timestamp() const
171 if(year<-289701 || year>293641)
172 throw Exception("DateTime is not representable as a TimeStamp");
174 int64_t raw=(((hour*60LL)+minute)*60+second)*1000000+usec;
175 int days=(year-1970)*365;
176 days+=(year-1)/4-(year-1)/100+(year-1)/400-477;
177 for(unsigned i=1; i<month; ++i)
178 days+=month_days(year, i);
181 raw+=days*86400000000LL;
183 return TimeStamp(raw);
186 string DateTime::format(const string &fmt) const
190 for(string::const_iterator i=fmt.begin(); i!=fmt.end(); ++i)
198 ss<<setw(2)<<int(mday);
200 ss<<setw(2)<<int(hour);
202 ss<<setw(2)<<hour%12;
204 ss<<setw(2)<<int(month);
206 ss<<setw(2)<<int(minute);
208 ss<<((hour>=12) ? "PM" : "AM");
210 ss<<setw(2)<<int(second);
212 ss<<setw(2)<<year%100;
225 void DateTime::add_raw(int64_t raw)
227 int32_t days=raw/86400000000LL;
235 usec+=raw%1000000; raw/=1000000;
236 second+=raw%60; raw/=60;
237 minute+=raw%60; raw/=60;
238 hour+=raw%24; raw/=24;
244 void DateTime::normalize()
246 second+=usec/1000000;
254 while(mday>month_days(year, month))
256 mday-=month_days(year, month);