4 #include "../core/except.h"
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)
46 DateTime::DateTime(const TimeStamp &ts):
58 DateTime::DateTime(int32_t y, uint8_t m, uint8_t d):
68 DateTime::DateTime(int32_t y, uint8_t m, uint8_t d, uint8_t h, uint8_t n, uint8_t s):
78 DateTime::DateTime(int32_t y, uint8_t m, uint8_t d, uint8_t h, uint8_t n, uint8_t s, uint32_t u):
88 void DateTime::add_days(int32_t days)
90 unsigned new_year=year;
92 /* Leap years have a 400 year cycle, so any 400 consecutive years have a
93 constant number of days (400*365+97=146097) */
94 new_year+=days/146097*400;
103 // Fudge factor for leap day
104 int fudge=(month<=2)?1:0;
106 // (Almost) every 4 year cycle has 1 leap year and 3 normal years
107 unsigned cycles=days/1461;
112 // See how many non-leap-years we counted as leap years and reclaim the lost days
113 unsigned missed_leap_days=((year-fudge)%100+cycles*4)/100;
114 if((year-fudge)%400+cycles*4>=400)
117 days+=missed_leap_days;
119 // Count single years from the 4 year cycle
125 if((year-fudge)%4+cycles>=4)
127 // We passed a leap year - decrement days
131 days=is_leap_year(new_year)?365:364;
140 while(mday+days>month_days(year, month))
142 days-=month_days(year, month);
154 DateTime DateTime::operator+(const TimeDelta &td) const
157 dt.add_raw(td.raw());
161 DateTime &DateTime::operator+=(const TimeDelta &td)
167 int DateTime::cmp(const DateTime &dt) const
169 if(int c=cmp_(year, dt.year))
171 if(int c=cmp_(month, dt.month))
173 if(int c=cmp_(mday, dt.mday))
175 if(int c=cmp_(hour, dt.hour))
177 if(int c=cmp_(minute, dt.minute))
179 if(int c=cmp_(second, dt.second))
181 if(int c=cmp_(usec, dt.usec))
186 TimeStamp DateTime::get_timestamp() const
188 if(year<-289701 || year>293641)
189 throw Exception("DateTime is not representable as a TimeStamp");
191 int64_t raw=(((hour*60LL)+minute)*60+second)*1000000+usec;
192 int days=(year-1970)*365;
193 days+=(year-1)/4-(year-1)/100+(year-1)/400-477;
194 for(unsigned i=1; i<month; ++i)
195 days+=month_days(year, i);
198 raw+=days*86400000000LL;
200 return TimeStamp(raw);
203 string DateTime::format(const string &fmt) const
207 for(string::const_iterator i=fmt.begin(); i!=fmt.end(); ++i)
215 ss<<setw(2)<<int(mday);
217 ss<<setw(2)<<int(hour);
219 ss<<setw(2)<<hour%12;
221 ss<<setw(2)<<int(month);
223 ss<<setw(2)<<int(minute);
225 ss<<((hour>=12) ? "PM" : "AM");
227 ss<<setw(2)<<int(second);
229 ss<<setw(2)<<year%100;
242 void DateTime::add_raw(int64_t raw)
244 int32_t days=raw/86400000000LL;
252 usec+=raw%1000000; raw/=1000000;
253 second+=raw%60; raw/=60;
254 minute+=raw%60; raw/=60;
255 hour+=raw%24; raw/=24;
261 void DateTime::normalize()
263 second+=usec/1000000;
271 while(mday>month_days(year, month))
273 mday-=month_days(year, month);