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