1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // The implementation of the absl::Time class, which is declared in
16 // //absl/time.h.
17 //
18 // The representation for an absl::Time is an absl::Duration offset from the
19 // epoch. We use the traditional Unix epoch (1970-01-01 00:00:00 +0000)
20 // for convenience, but this is not exposed in the API and could be changed.
21 //
22 // NOTE: To keep type verbosity to a minimum, the following variable naming
23 // conventions are used throughout this file.
24 //
25 // tz: An absl::TimeZone
26 // ci: An absl::TimeZone::CivilInfo
27 // ti: An absl::TimeZone::TimeInfo
28 // cd: An absl::CivilDay or a cctz::civil_day
29 // cs: An absl::CivilSecond or a cctz::civil_second
30 // bd: An absl::Time::Breakdown
31 // cl: A cctz::time_zone::civil_lookup
32 // al: A cctz::time_zone::absolute_lookup
33
34 #include "absl/time/time.h"
35
36 #if defined(_MSC_VER)
37 #include <winsock2.h> // for timeval
38 #endif
39
40 #include <cstring>
41 #include <ctime>
42 #include <limits>
43
44 #include "absl/time/internal/cctz/include/cctz/civil_time.h"
45 #include "absl/time/internal/cctz/include/cctz/time_zone.h"
46
47 namespace cctz = absl::time_internal::cctz;
48
49 namespace absl {
50 ABSL_NAMESPACE_BEGIN
51
52 namespace {
53
unix_epoch()54 inline cctz::time_point<cctz::seconds> unix_epoch() {
55 return std::chrono::time_point_cast<cctz::seconds>(
56 std::chrono::system_clock::from_time_t(0));
57 }
58
59 // Floors d to the next unit boundary closer to negative infinity.
FloorToUnit(absl::Duration d,absl::Duration unit)60 inline int64_t FloorToUnit(absl::Duration d, absl::Duration unit) {
61 absl::Duration rem;
62 int64_t q = absl::IDivDuration(d, unit, &rem);
63 return (q > 0 || rem >= ZeroDuration() ||
64 q == std::numeric_limits<int64_t>::min())
65 ? q
66 : q - 1;
67 }
68
InfiniteFutureBreakdown()69 inline absl::Time::Breakdown InfiniteFutureBreakdown() {
70 absl::Time::Breakdown bd;
71 bd.year = std::numeric_limits<int64_t>::max();
72 bd.month = 12;
73 bd.day = 31;
74 bd.hour = 23;
75 bd.minute = 59;
76 bd.second = 59;
77 bd.subsecond = absl::InfiniteDuration();
78 bd.weekday = 4;
79 bd.yearday = 365;
80 bd.offset = 0;
81 bd.is_dst = false;
82 bd.zone_abbr = "-00";
83 return bd;
84 }
85
InfinitePastBreakdown()86 inline absl::Time::Breakdown InfinitePastBreakdown() {
87 Time::Breakdown bd;
88 bd.year = std::numeric_limits<int64_t>::min();
89 bd.month = 1;
90 bd.day = 1;
91 bd.hour = 0;
92 bd.minute = 0;
93 bd.second = 0;
94 bd.subsecond = -absl::InfiniteDuration();
95 bd.weekday = 7;
96 bd.yearday = 1;
97 bd.offset = 0;
98 bd.is_dst = false;
99 bd.zone_abbr = "-00";
100 return bd;
101 }
102
InfiniteFutureCivilInfo()103 inline absl::TimeZone::CivilInfo InfiniteFutureCivilInfo() {
104 TimeZone::CivilInfo ci;
105 ci.cs = CivilSecond::max();
106 ci.subsecond = InfiniteDuration();
107 ci.offset = 0;
108 ci.is_dst = false;
109 ci.zone_abbr = "-00";
110 return ci;
111 }
112
InfinitePastCivilInfo()113 inline absl::TimeZone::CivilInfo InfinitePastCivilInfo() {
114 TimeZone::CivilInfo ci;
115 ci.cs = CivilSecond::min();
116 ci.subsecond = -InfiniteDuration();
117 ci.offset = 0;
118 ci.is_dst = false;
119 ci.zone_abbr = "-00";
120 return ci;
121 }
122
InfiniteFutureTimeConversion()123 inline absl::TimeConversion InfiniteFutureTimeConversion() {
124 absl::TimeConversion tc;
125 tc.pre = tc.trans = tc.post = absl::InfiniteFuture();
126 tc.kind = absl::TimeConversion::UNIQUE;
127 tc.normalized = true;
128 return tc;
129 }
130
InfinitePastTimeConversion()131 inline TimeConversion InfinitePastTimeConversion() {
132 absl::TimeConversion tc;
133 tc.pre = tc.trans = tc.post = absl::InfinitePast();
134 tc.kind = absl::TimeConversion::UNIQUE;
135 tc.normalized = true;
136 return tc;
137 }
138
139 // Makes a Time from sec, overflowing to InfiniteFuture/InfinitePast as
140 // necessary. If sec is min/max, then consult cs+tz to check for overlow.
MakeTimeWithOverflow(const cctz::time_point<cctz::seconds> & sec,const cctz::civil_second & cs,const cctz::time_zone & tz,bool * normalized=nullptr)141 Time MakeTimeWithOverflow(const cctz::time_point<cctz::seconds>& sec,
142 const cctz::civil_second& cs,
143 const cctz::time_zone& tz,
144 bool* normalized = nullptr) {
145 const auto max = cctz::time_point<cctz::seconds>::max();
146 const auto min = cctz::time_point<cctz::seconds>::min();
147 if (sec == max) {
148 const auto al = tz.lookup(max);
149 if (cs > al.cs) {
150 if (normalized) *normalized = true;
151 return absl::InfiniteFuture();
152 }
153 }
154 if (sec == min) {
155 const auto al = tz.lookup(min);
156 if (cs < al.cs) {
157 if (normalized) *normalized = true;
158 return absl::InfinitePast();
159 }
160 }
161 const auto hi = (sec - unix_epoch()).count();
162 return time_internal::FromUnixDuration(time_internal::MakeDuration(hi));
163 }
164
165 // Returns Mon=1..Sun=7.
MapWeekday(const cctz::weekday & wd)166 inline int MapWeekday(const cctz::weekday& wd) {
167 switch (wd) {
168 case cctz::weekday::monday:
169 return 1;
170 case cctz::weekday::tuesday:
171 return 2;
172 case cctz::weekday::wednesday:
173 return 3;
174 case cctz::weekday::thursday:
175 return 4;
176 case cctz::weekday::friday:
177 return 5;
178 case cctz::weekday::saturday:
179 return 6;
180 case cctz::weekday::sunday:
181 return 7;
182 }
183 return 1;
184 }
185
FindTransition(const cctz::time_zone & tz,bool (cctz::time_zone::* find_transition)(const cctz::time_point<cctz::seconds> & tp,cctz::time_zone::civil_transition * trans)const,Time t,TimeZone::CivilTransition * trans)186 bool FindTransition(const cctz::time_zone& tz,
187 bool (cctz::time_zone::*find_transition)(
188 const cctz::time_point<cctz::seconds>& tp,
189 cctz::time_zone::civil_transition* trans) const,
190 Time t, TimeZone::CivilTransition* trans) {
191 // Transitions are second-aligned, so we can discard any fractional part.
192 const auto tp = unix_epoch() + cctz::seconds(ToUnixSeconds(t));
193 cctz::time_zone::civil_transition tr;
194 if (!(tz.*find_transition)(tp, &tr)) return false;
195 trans->from = CivilSecond(tr.from);
196 trans->to = CivilSecond(tr.to);
197 return true;
198 }
199
200 } // namespace
201
202 //
203 // Time
204 //
205
In(absl::TimeZone tz) const206 absl::Time::Breakdown Time::In(absl::TimeZone tz) const {
207 if (*this == absl::InfiniteFuture()) return InfiniteFutureBreakdown();
208 if (*this == absl::InfinitePast()) return InfinitePastBreakdown();
209
210 const auto tp = unix_epoch() + cctz::seconds(time_internal::GetRepHi(rep_));
211 const auto al = cctz::time_zone(tz).lookup(tp);
212 const auto cs = al.cs;
213 const auto cd = cctz::civil_day(cs);
214
215 absl::Time::Breakdown bd;
216 bd.year = cs.year();
217 bd.month = cs.month();
218 bd.day = cs.day();
219 bd.hour = cs.hour();
220 bd.minute = cs.minute();
221 bd.second = cs.second();
222 bd.subsecond = time_internal::MakeDuration(0, time_internal::GetRepLo(rep_));
223 bd.weekday = MapWeekday(cctz::get_weekday(cd));
224 bd.yearday = cctz::get_yearday(cd);
225 bd.offset = al.offset;
226 bd.is_dst = al.is_dst;
227 bd.zone_abbr = al.abbr;
228 return bd;
229 }
230
231 //
232 // Conversions from/to other time types.
233 //
234
FromUDate(double udate)235 absl::Time FromUDate(double udate) {
236 return time_internal::FromUnixDuration(absl::Milliseconds(udate));
237 }
238
FromUniversal(int64_t universal)239 absl::Time FromUniversal(int64_t universal) {
240 return absl::UniversalEpoch() + 100 * absl::Nanoseconds(universal);
241 }
242
ToUnixNanos(Time t)243 int64_t ToUnixNanos(Time t) {
244 if (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >= 0 &&
245 time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >> 33 == 0) {
246 return (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) *
247 1000 * 1000 * 1000) +
248 (time_internal::GetRepLo(time_internal::ToUnixDuration(t)) / 4);
249 }
250 return FloorToUnit(time_internal::ToUnixDuration(t), absl::Nanoseconds(1));
251 }
252
ToUnixMicros(Time t)253 int64_t ToUnixMicros(Time t) {
254 if (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >= 0 &&
255 time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >> 43 == 0) {
256 return (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) *
257 1000 * 1000) +
258 (time_internal::GetRepLo(time_internal::ToUnixDuration(t)) / 4000);
259 }
260 return FloorToUnit(time_internal::ToUnixDuration(t), absl::Microseconds(1));
261 }
262
ToUnixMillis(Time t)263 int64_t ToUnixMillis(Time t) {
264 if (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >= 0 &&
265 time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >> 53 == 0) {
266 return (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) * 1000) +
267 (time_internal::GetRepLo(time_internal::ToUnixDuration(t)) /
268 (4000 * 1000));
269 }
270 return FloorToUnit(time_internal::ToUnixDuration(t), absl::Milliseconds(1));
271 }
272
ToUnixSeconds(Time t)273 int64_t ToUnixSeconds(Time t) {
274 return time_internal::GetRepHi(time_internal::ToUnixDuration(t));
275 }
276
ToTimeT(Time t)277 time_t ToTimeT(Time t) { return absl::ToTimespec(t).tv_sec; }
278
ToUDate(Time t)279 double ToUDate(Time t) {
280 return absl::FDivDuration(time_internal::ToUnixDuration(t),
281 absl::Milliseconds(1));
282 }
283
ToUniversal(absl::Time t)284 int64_t ToUniversal(absl::Time t) {
285 return absl::FloorToUnit(t - absl::UniversalEpoch(), absl::Nanoseconds(100));
286 }
287
TimeFromTimespec(timespec ts)288 absl::Time TimeFromTimespec(timespec ts) {
289 return time_internal::FromUnixDuration(absl::DurationFromTimespec(ts));
290 }
291
TimeFromTimeval(timeval tv)292 absl::Time TimeFromTimeval(timeval tv) {
293 return time_internal::FromUnixDuration(absl::DurationFromTimeval(tv));
294 }
295
ToTimespec(Time t)296 timespec ToTimespec(Time t) {
297 timespec ts;
298 absl::Duration d = time_internal::ToUnixDuration(t);
299 if (!time_internal::IsInfiniteDuration(d)) {
300 ts.tv_sec = time_internal::GetRepHi(d);
301 if (ts.tv_sec == time_internal::GetRepHi(d)) { // no time_t narrowing
302 ts.tv_nsec = time_internal::GetRepLo(d) / 4; // floor
303 return ts;
304 }
305 }
306 if (d >= absl::ZeroDuration()) {
307 ts.tv_sec = std::numeric_limits<time_t>::max();
308 ts.tv_nsec = 1000 * 1000 * 1000 - 1;
309 } else {
310 ts.tv_sec = std::numeric_limits<time_t>::min();
311 ts.tv_nsec = 0;
312 }
313 return ts;
314 }
315
ToTimeval(Time t)316 timeval ToTimeval(Time t) {
317 timeval tv;
318 timespec ts = absl::ToTimespec(t);
319 tv.tv_sec = ts.tv_sec;
320 if (tv.tv_sec != ts.tv_sec) { // narrowing
321 if (ts.tv_sec < 0) {
322 tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::min();
323 tv.tv_usec = 0;
324 } else {
325 tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::max();
326 tv.tv_usec = 1000 * 1000 - 1;
327 }
328 return tv;
329 }
330 tv.tv_usec = static_cast<int>(ts.tv_nsec / 1000); // suseconds_t
331 return tv;
332 }
333
FromChrono(const std::chrono::system_clock::time_point & tp)334 Time FromChrono(const std::chrono::system_clock::time_point& tp) {
335 return time_internal::FromUnixDuration(time_internal::FromChrono(
336 tp - std::chrono::system_clock::from_time_t(0)));
337 }
338
ToChronoTime(absl::Time t)339 std::chrono::system_clock::time_point ToChronoTime(absl::Time t) {
340 using D = std::chrono::system_clock::duration;
341 auto d = time_internal::ToUnixDuration(t);
342 if (d < ZeroDuration()) d = Floor(d, FromChrono(D{1}));
343 return std::chrono::system_clock::from_time_t(0) +
344 time_internal::ToChronoDuration<D>(d);
345 }
346
347 //
348 // TimeZone
349 //
350
At(Time t) const351 absl::TimeZone::CivilInfo TimeZone::At(Time t) const {
352 if (t == absl::InfiniteFuture()) return InfiniteFutureCivilInfo();
353 if (t == absl::InfinitePast()) return InfinitePastCivilInfo();
354
355 const auto ud = time_internal::ToUnixDuration(t);
356 const auto tp = unix_epoch() + cctz::seconds(time_internal::GetRepHi(ud));
357 const auto al = cz_.lookup(tp);
358
359 TimeZone::CivilInfo ci;
360 ci.cs = CivilSecond(al.cs);
361 ci.subsecond = time_internal::MakeDuration(0, time_internal::GetRepLo(ud));
362 ci.offset = al.offset;
363 ci.is_dst = al.is_dst;
364 ci.zone_abbr = al.abbr;
365 return ci;
366 }
367
At(CivilSecond ct) const368 absl::TimeZone::TimeInfo TimeZone::At(CivilSecond ct) const {
369 const cctz::civil_second cs(ct);
370 const auto cl = cz_.lookup(cs);
371
372 TimeZone::TimeInfo ti;
373 switch (cl.kind) {
374 case cctz::time_zone::civil_lookup::UNIQUE:
375 ti.kind = TimeZone::TimeInfo::UNIQUE;
376 break;
377 case cctz::time_zone::civil_lookup::SKIPPED:
378 ti.kind = TimeZone::TimeInfo::SKIPPED;
379 break;
380 case cctz::time_zone::civil_lookup::REPEATED:
381 ti.kind = TimeZone::TimeInfo::REPEATED;
382 break;
383 }
384 ti.pre = MakeTimeWithOverflow(cl.pre, cs, cz_);
385 ti.trans = MakeTimeWithOverflow(cl.trans, cs, cz_);
386 ti.post = MakeTimeWithOverflow(cl.post, cs, cz_);
387 return ti;
388 }
389
NextTransition(Time t,CivilTransition * trans) const390 bool TimeZone::NextTransition(Time t, CivilTransition* trans) const {
391 return FindTransition(cz_, &cctz::time_zone::next_transition, t, trans);
392 }
393
PrevTransition(Time t,CivilTransition * trans) const394 bool TimeZone::PrevTransition(Time t, CivilTransition* trans) const {
395 return FindTransition(cz_, &cctz::time_zone::prev_transition, t, trans);
396 }
397
398 //
399 // Conversions involving time zones.
400 //
401
ConvertDateTime(int64_t year,int mon,int day,int hour,int min,int sec,TimeZone tz)402 absl::TimeConversion ConvertDateTime(int64_t year, int mon, int day, int hour,
403 int min, int sec, TimeZone tz) {
404 // Avoids years that are too extreme for CivilSecond to normalize.
405 if (year > 300000000000) return InfiniteFutureTimeConversion();
406 if (year < -300000000000) return InfinitePastTimeConversion();
407
408 const CivilSecond cs(year, mon, day, hour, min, sec);
409 const auto ti = tz.At(cs);
410
411 TimeConversion tc;
412 tc.pre = ti.pre;
413 tc.trans = ti.trans;
414 tc.post = ti.post;
415 switch (ti.kind) {
416 case TimeZone::TimeInfo::UNIQUE:
417 tc.kind = TimeConversion::UNIQUE;
418 break;
419 case TimeZone::TimeInfo::SKIPPED:
420 tc.kind = TimeConversion::SKIPPED;
421 break;
422 case TimeZone::TimeInfo::REPEATED:
423 tc.kind = TimeConversion::REPEATED;
424 break;
425 }
426 tc.normalized = false;
427 if (year != cs.year() || mon != cs.month() || day != cs.day() ||
428 hour != cs.hour() || min != cs.minute() || sec != cs.second()) {
429 tc.normalized = true;
430 }
431 return tc;
432 }
433
FromTM(const struct tm & tm,absl::TimeZone tz)434 absl::Time FromTM(const struct tm& tm, absl::TimeZone tz) {
435 civil_year_t tm_year = tm.tm_year;
436 // Avoids years that are too extreme for CivilSecond to normalize.
437 if (tm_year > 300000000000ll) return InfiniteFuture();
438 if (tm_year < -300000000000ll) return InfinitePast();
439 int tm_mon = tm.tm_mon;
440 if (tm_mon == std::numeric_limits<int>::max()) {
441 tm_mon -= 12;
442 tm_year += 1;
443 }
444 const auto ti = tz.At(CivilSecond(tm_year + 1900, tm_mon + 1, tm.tm_mday,
445 tm.tm_hour, tm.tm_min, tm.tm_sec));
446 return tm.tm_isdst == 0 ? ti.post : ti.pre;
447 }
448
ToTM(absl::Time t,absl::TimeZone tz)449 struct tm ToTM(absl::Time t, absl::TimeZone tz) {
450 struct tm tm = {};
451
452 const auto ci = tz.At(t);
453 const auto& cs = ci.cs;
454 tm.tm_sec = cs.second();
455 tm.tm_min = cs.minute();
456 tm.tm_hour = cs.hour();
457 tm.tm_mday = cs.day();
458 tm.tm_mon = cs.month() - 1;
459
460 // Saturates tm.tm_year in cases of over/underflow, accounting for the fact
461 // that tm.tm_year is years since 1900.
462 if (cs.year() < std::numeric_limits<int>::min() + 1900) {
463 tm.tm_year = std::numeric_limits<int>::min();
464 } else if (cs.year() > std::numeric_limits<int>::max()) {
465 tm.tm_year = std::numeric_limits<int>::max() - 1900;
466 } else {
467 tm.tm_year = static_cast<int>(cs.year() - 1900);
468 }
469
470 switch (GetWeekday(cs)) {
471 case Weekday::sunday:
472 tm.tm_wday = 0;
473 break;
474 case Weekday::monday:
475 tm.tm_wday = 1;
476 break;
477 case Weekday::tuesday:
478 tm.tm_wday = 2;
479 break;
480 case Weekday::wednesday:
481 tm.tm_wday = 3;
482 break;
483 case Weekday::thursday:
484 tm.tm_wday = 4;
485 break;
486 case Weekday::friday:
487 tm.tm_wday = 5;
488 break;
489 case Weekday::saturday:
490 tm.tm_wday = 6;
491 break;
492 }
493 tm.tm_yday = GetYearDay(cs) - 1;
494 tm.tm_isdst = ci.is_dst ? 1 : 0;
495
496 return tm;
497 }
498
499 ABSL_NAMESPACE_END
500 } // namespace absl
501