• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // -----------------------------------------------------------------------------
16 // File: time.h
17 // -----------------------------------------------------------------------------
18 //
19 // This header file defines abstractions for computing with absolute points
20 // in time, durations of time, and formatting and parsing time within a given
21 // time zone. The following abstractions are defined:
22 //
23 //  * `absl::Time` defines an absolute, specific instance in time
24 //  * `absl::Duration` defines a signed, fixed-length span of time
25 //  * `absl::TimeZone` defines geopolitical time zone regions (as collected
26 //     within the IANA Time Zone database (https://www.iana.org/time-zones)).
27 //
28 // Note: Absolute times are distinct from civil times, which refer to the
29 // human-scale time commonly represented by `YYYY-MM-DD hh:mm:ss`. The mapping
30 // between absolute and civil times can be specified by use of time zones
31 // (`absl::TimeZone` within this API). That is:
32 //
33 //   Civil Time = F(Absolute Time, Time Zone)
34 //   Absolute Time = G(Civil Time, Time Zone)
35 //
36 // See civil_time.h for abstractions related to constructing and manipulating
37 // civil time.
38 //
39 // Example:
40 //
41 //   absl::TimeZone nyc;
42 //   // LoadTimeZone() may fail so it's always better to check for success.
43 //   if (!absl::LoadTimeZone("America/New_York", &nyc)) {
44 //      // handle error case
45 //   }
46 //
47 //   // My flight leaves NYC on Jan 2, 2017 at 03:04:05
48 //   absl::CivilSecond cs(2017, 1, 2, 3, 4, 5);
49 //   absl::Time takeoff = absl::FromCivil(cs, nyc);
50 //
51 //   absl::Duration flight_duration = absl::Hours(21) + absl::Minutes(35);
52 //   absl::Time landing = takeoff + flight_duration;
53 //
54 //   absl::TimeZone syd;
55 //   if (!absl::LoadTimeZone("Australia/Sydney", &syd)) {
56 //      // handle error case
57 //   }
58 //   std::string s = absl::FormatTime(
59 //       "My flight will land in Sydney on %Y-%m-%d at %H:%M:%S",
60 //       landing, syd);
61 
62 #ifndef ABSL_TIME_TIME_H_
63 #define ABSL_TIME_TIME_H_
64 
65 #if !defined(_MSC_VER)
66 #include <sys/time.h>
67 #else
68 // We don't include `winsock2.h` because it drags in `windows.h` and friends,
69 // and they define conflicting macros like OPAQUE, ERROR, and more. This has the
70 // potential to break Abseil users.
71 //
72 // Instead we only forward declare `timeval` and require Windows users include
73 // `winsock2.h` themselves. This is both inconsistent and troublesome, but so is
74 // including 'windows.h' so we are picking the lesser of two evils here.
75 struct timeval;
76 #endif
77 #include <chrono>  // NOLINT(build/c++11)
78 #include <cmath>
79 #include <cstdint>
80 #include <ctime>
81 #include <limits>
82 #include <ostream>
83 #include <string>
84 #include <type_traits>
85 #include <utility>
86 
87 #include "absl/base/config.h"
88 #include "absl/base/macros.h"
89 #include "absl/strings/string_view.h"
90 #include "absl/time/civil_time.h"
91 #include "absl/time/internal/cctz/include/cctz/time_zone.h"
92 
93 namespace absl {
94 ABSL_NAMESPACE_BEGIN
95 
96 class Duration;  // Defined below
97 class Time;      // Defined below
98 class TimeZone;  // Defined below
99 
100 namespace time_internal {
101 int64_t IDivDuration(bool satq, Duration num, Duration den, Duration* rem);
102 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixDuration(Duration d);
103 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration ToUnixDuration(Time t);
104 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t GetRepHi(Duration d);
105 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr uint32_t GetRepLo(Duration d);
106 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeDuration(int64_t hi,
107                                                               uint32_t lo);
108 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeDuration(int64_t hi,
109                                                               int64_t lo);
110 ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration MakePosDoubleDuration(double n);
111 constexpr int64_t kTicksPerNanosecond = 4;
112 constexpr int64_t kTicksPerSecond = 1000 * 1000 * 1000 * kTicksPerNanosecond;
113 template <std::intmax_t N>
114 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
115                                                            std::ratio<1, N>);
116 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
117                                                            std::ratio<60>);
118 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
119                                                            std::ratio<3600>);
120 template <typename T>
121 using EnableIfIntegral = typename std::enable_if<
122     std::is_integral<T>::value || std::is_enum<T>::value, int>::type;
123 template <typename T>
124 using EnableIfFloat =
125     typename std::enable_if<std::is_floating_point<T>::value, int>::type;
126 }  // namespace time_internal
127 
128 // Duration
129 //
130 // The `absl::Duration` class represents a signed, fixed-length amount of time.
131 // A `Duration` is generated using a unit-specific factory function, or is
132 // the result of subtracting one `absl::Time` from another. Durations behave
133 // like unit-safe integers and they support all the natural integer-like
134 // arithmetic operations. Arithmetic overflows and saturates at +/- infinity.
135 // `Duration` should be passed by value rather than const reference.
136 //
137 // Factory functions `Nanoseconds()`, `Microseconds()`, `Milliseconds()`,
138 // `Seconds()`, `Minutes()`, `Hours()` and `InfiniteDuration()` allow for
139 // creation of constexpr `Duration` values
140 //
141 // Examples:
142 //
143 //   constexpr absl::Duration ten_ns = absl::Nanoseconds(10);
144 //   constexpr absl::Duration min = absl::Minutes(1);
145 //   constexpr absl::Duration hour = absl::Hours(1);
146 //   absl::Duration dur = 60 * min;  // dur == hour
147 //   absl::Duration half_sec = absl::Milliseconds(500);
148 //   absl::Duration quarter_sec = 0.25 * absl::Seconds(1);
149 //
150 // `Duration` values can be easily converted to an integral number of units
151 // using the division operator.
152 //
153 // Example:
154 //
155 //   constexpr absl::Duration dur = absl::Milliseconds(1500);
156 //   int64_t ns = dur / absl::Nanoseconds(1);   // ns == 1500000000
157 //   int64_t ms = dur / absl::Milliseconds(1);  // ms == 1500
158 //   int64_t sec = dur / absl::Seconds(1);    // sec == 1 (subseconds truncated)
159 //   int64_t min = dur / absl::Minutes(1);    // min == 0
160 //
161 // See the `IDivDuration()` and `FDivDuration()` functions below for details on
162 // how to access the fractional parts of the quotient.
163 //
164 // Alternatively, conversions can be performed using helpers such as
165 // `ToInt64Microseconds()` and `ToDoubleSeconds()`.
166 class Duration {
167  public:
168   // Value semantics.
Duration()169   constexpr Duration() : rep_hi_(0), rep_lo_(0) {}  // zero-length duration
170 
171   // Copyable.
172 #if !defined(__clang__) && defined(_MSC_VER) && _MSC_VER < 1930
173   // Explicitly defining the constexpr copy constructor avoids an MSVC bug.
Duration(const Duration & d)174   constexpr Duration(const Duration& d)
175       : rep_hi_(d.rep_hi_), rep_lo_(d.rep_lo_) {}
176 #else
177   constexpr Duration(const Duration& d) = default;
178 #endif
179   Duration& operator=(const Duration& d) = default;
180 
181   // Compound assignment operators.
182   Duration& operator+=(Duration d);
183   Duration& operator-=(Duration d);
184   Duration& operator*=(int64_t r);
185   Duration& operator*=(double r);
186   Duration& operator/=(int64_t r);
187   Duration& operator/=(double r);
188   Duration& operator%=(Duration rhs);
189 
190   // Overloads that forward to either the int64_t or double overloads above.
191   // Integer operands must be representable as int64_t. Integer division is
192   // truncating, so values less than the resolution will be returned as zero.
193   // Floating-point multiplication and division is rounding (halfway cases
194   // rounding away from zero), so values less than the resolution may be
195   // returned as either the resolution or zero.  In particular, `d / 2.0`
196   // can produce `d` when it is the resolution and "even".
197   template <typename T, time_internal::EnableIfIntegral<T> = 0>
198   Duration& operator*=(T r) {
199     int64_t x = r;
200     return *this *= x;
201   }
202 
203   template <typename T, time_internal::EnableIfIntegral<T> = 0>
204   Duration& operator/=(T r) {
205     int64_t x = r;
206     return *this /= x;
207   }
208 
209   template <typename T, time_internal::EnableIfFloat<T> = 0>
210   Duration& operator*=(T r) {
211     double x = r;
212     return *this *= x;
213   }
214 
215   template <typename T, time_internal::EnableIfFloat<T> = 0>
216   Duration& operator/=(T r) {
217     double x = r;
218     return *this /= x;
219   }
220 
221   template <typename H>
AbslHashValue(H h,Duration d)222   friend H AbslHashValue(H h, Duration d) {
223     return H::combine(std::move(h), d.rep_hi_.Get(), d.rep_lo_);
224   }
225 
226  private:
227   friend constexpr int64_t time_internal::GetRepHi(Duration d);
228   friend constexpr uint32_t time_internal::GetRepLo(Duration d);
229   friend constexpr Duration time_internal::MakeDuration(int64_t hi,
230                                                         uint32_t lo);
Duration(int64_t hi,uint32_t lo)231   constexpr Duration(int64_t hi, uint32_t lo) : rep_hi_(hi), rep_lo_(lo) {}
232 
233   // We store `rep_hi_` 4-byte rather than 8-byte aligned to avoid 4 bytes of
234   // tail padding.
235   class HiRep {
236    public:
237     // Default constructor default-initializes `hi_`, which has the same
238     // semantics as default-initializing an `int64_t` (undetermined value).
239     HiRep() = default;
240 
241     HiRep(const HiRep&) = default;
242     HiRep& operator=(const HiRep&) = default;
243 
HiRep(const int64_t value)244     explicit constexpr HiRep(const int64_t value)
245         :  // C++17 forbids default-initialization in constexpr contexts. We can
246            // remove this in C++20.
247 #if defined(ABSL_IS_BIG_ENDIAN) && ABSL_IS_BIG_ENDIAN
248           hi_(0),
249           lo_(0)
250 #else
251           lo_(0),
252           hi_(0)
253 #endif
254     {
255       *this = value;
256     }
257 
Get()258     constexpr int64_t Get() const {
259       const uint64_t unsigned_value =
260           (static_cast<uint64_t>(hi_) << 32) | static_cast<uint64_t>(lo_);
261       // `static_cast<int64_t>(unsigned_value)` is implementation-defined
262       // before c++20. On all supported platforms the behaviour is that mandated
263       // by c++20, i.e. "If the destination type is signed, [...] the result is
264       // the unique value of the destination type equal to the source value
265       // modulo 2^n, where n is the number of bits used to represent the
266       // destination type."
267       static_assert(
268           (static_cast<int64_t>((std::numeric_limits<uint64_t>::max)()) ==
269            int64_t{-1}) &&
270               (static_cast<int64_t>(static_cast<uint64_t>(
271                                         (std::numeric_limits<int64_t>::max)()) +
272                                     1) ==
273                (std::numeric_limits<int64_t>::min)()),
274           "static_cast<int64_t>(uint64_t) does not have c++20 semantics");
275       return static_cast<int64_t>(unsigned_value);
276     }
277 
278     constexpr HiRep& operator=(const int64_t value) {
279       // "If the destination type is unsigned, the resulting value is the
280       // smallest unsigned value equal to the source value modulo 2^n
281       // where `n` is the number of bits used to represent the destination
282       // type".
283       const auto unsigned_value = static_cast<uint64_t>(value);
284       hi_ = static_cast<uint32_t>(unsigned_value >> 32);
285       lo_ = static_cast<uint32_t>(unsigned_value);
286       return *this;
287     }
288 
289    private:
290     // Notes:
291     //  - Ideally we would use a `char[]` and `std::bitcast`, but the latter
292     //    does not exist (and is not constexpr in `absl`) before c++20.
293     //  - Order is optimized depending on endianness so that the compiler can
294     //    turn `Get()` (resp. `operator=()`) into a single 8-byte load (resp.
295     //    store).
296 #if defined(ABSL_IS_BIG_ENDIAN) && ABSL_IS_BIG_ENDIAN
297     uint32_t hi_;
298     uint32_t lo_;
299 #else
300     uint32_t lo_;
301     uint32_t hi_;
302 #endif
303   };
304   HiRep rep_hi_;
305   uint32_t rep_lo_;
306 };
307 
308 // Relational Operators
309 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<(Duration lhs,
310                                                        Duration rhs);
311 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>(Duration lhs,
312                                                        Duration rhs) {
313   return rhs < lhs;
314 }
315 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>=(Duration lhs,
316                                                         Duration rhs) {
317   return !(lhs < rhs);
318 }
319 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<=(Duration lhs,
320                                                         Duration rhs) {
321   return !(rhs < lhs);
322 }
323 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator==(Duration lhs,
324                                                         Duration rhs);
325 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator!=(Duration lhs,
326                                                         Duration rhs) {
327   return !(lhs == rhs);
328 }
329 
330 // Additive Operators
331 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration operator-(Duration d);
332 ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator+(Duration lhs,
333                                                         Duration rhs) {
334   return lhs += rhs;
335 }
336 ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator-(Duration lhs,
337                                                         Duration rhs) {
338   return lhs -= rhs;
339 }
340 
341 // Multiplicative Operators
342 // Integer operands must be representable as int64_t.
343 template <typename T>
344 ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator*(Duration lhs, T rhs) {
345   return lhs *= rhs;
346 }
347 template <typename T>
348 ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator*(T lhs, Duration rhs) {
349   return rhs *= lhs;
350 }
351 template <typename T>
352 ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator/(Duration lhs, T rhs) {
353   return lhs /= rhs;
354 }
355 ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t operator/(Duration lhs,
356                                                        Duration rhs) {
357   return time_internal::IDivDuration(true, lhs, rhs,
358                                      &lhs);  // trunc towards zero
359 }
360 ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator%(Duration lhs,
361                                                         Duration rhs) {
362   return lhs %= rhs;
363 }
364 
365 // IDivDuration()
366 //
367 // Divides a numerator `Duration` by a denominator `Duration`, returning the
368 // quotient and remainder. The remainder always has the same sign as the
369 // numerator. The returned quotient and remainder respect the identity:
370 //
371 //   numerator = denominator * quotient + remainder
372 //
373 // Returned quotients are capped to the range of `int64_t`, with the difference
374 // spilling into the remainder to uphold the above identity. This means that the
375 // remainder returned could differ from the remainder returned by
376 // `Duration::operator%` for huge quotients.
377 //
378 // See also the notes on `InfiniteDuration()` below regarding the behavior of
379 // division involving zero and infinite durations.
380 //
381 // Example:
382 //
383 //   constexpr absl::Duration a =
384 //       absl::Seconds(std::numeric_limits<int64_t>::max());  // big
385 //   constexpr absl::Duration b = absl::Nanoseconds(1);       // small
386 //
387 //   absl::Duration rem = a % b;
388 //   // rem == absl::ZeroDuration()
389 //
390 //   // Here, q would overflow int64_t, so rem accounts for the difference.
391 //   int64_t q = absl::IDivDuration(a, b, &rem);
392 //   // q == std::numeric_limits<int64_t>::max(), rem == a - b * q
IDivDuration(Duration num,Duration den,Duration * rem)393 inline int64_t IDivDuration(Duration num, Duration den, Duration* rem) {
394   return time_internal::IDivDuration(true, num, den,
395                                      rem);  // trunc towards zero
396 }
397 
398 // FDivDuration()
399 //
400 // Divides a `Duration` numerator into a fractional number of units of a
401 // `Duration` denominator.
402 //
403 // See also the notes on `InfiniteDuration()` below regarding the behavior of
404 // division involving zero and infinite durations.
405 //
406 // Example:
407 //
408 //   double d = absl::FDivDuration(absl::Milliseconds(1500), absl::Seconds(1));
409 //   // d == 1.5
410 ABSL_ATTRIBUTE_CONST_FUNCTION double FDivDuration(Duration num, Duration den);
411 
412 // ZeroDuration()
413 //
414 // Returns a zero-length duration. This function behaves just like the default
415 // constructor, but the name helps make the semantics clear at call sites.
ZeroDuration()416 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration ZeroDuration() {
417   return Duration();
418 }
419 
420 // AbsDuration()
421 //
422 // Returns the absolute value of a duration.
AbsDuration(Duration d)423 ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration AbsDuration(Duration d) {
424   return (d < ZeroDuration()) ? -d : d;
425 }
426 
427 // Trunc()
428 //
429 // Truncates a duration (toward zero) to a multiple of a non-zero unit.
430 //
431 // Example:
432 //
433 //   absl::Duration d = absl::Nanoseconds(123456789);
434 //   absl::Duration a = absl::Trunc(d, absl::Microseconds(1));  // 123456us
435 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Trunc(Duration d, Duration unit);
436 
437 // Floor()
438 //
439 // Floors a duration using the passed duration unit to its largest value not
440 // greater than the duration.
441 //
442 // Example:
443 //
444 //   absl::Duration d = absl::Nanoseconds(123456789);
445 //   absl::Duration b = absl::Floor(d, absl::Microseconds(1));  // 123456us
446 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Floor(Duration d, Duration unit);
447 
448 // Ceil()
449 //
450 // Returns the ceiling of a duration using the passed duration unit to its
451 // smallest value not less than the duration.
452 //
453 // Example:
454 //
455 //   absl::Duration d = absl::Nanoseconds(123456789);
456 //   absl::Duration c = absl::Ceil(d, absl::Microseconds(1));   // 123457us
457 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Ceil(Duration d, Duration unit);
458 
459 // InfiniteDuration()
460 //
461 // Returns an infinite `Duration`.  To get a `Duration` representing negative
462 // infinity, use `-InfiniteDuration()`.
463 //
464 // Duration arithmetic overflows to +/- infinity and saturates. In general,
465 // arithmetic with `Duration` infinities is similar to IEEE 754 infinities
466 // except where IEEE 754 NaN would be involved, in which case +/-
467 // `InfiniteDuration()` is used in place of a "nan" Duration.
468 //
469 // Examples:
470 //
471 //   constexpr absl::Duration inf = absl::InfiniteDuration();
472 //   const absl::Duration d = ... any finite duration ...
473 //
474 //   inf == inf + inf
475 //   inf == inf + d
476 //   inf == inf - inf
477 //   -inf == d - inf
478 //
479 //   inf == d * 1e100
480 //   inf == inf / 2
481 //   0 == d / inf
482 //   INT64_MAX == inf / d
483 //
484 //   d < inf
485 //   -inf < d
486 //
487 //   // Division by zero returns infinity, or INT64_MIN/MAX where appropriate.
488 //   inf == d / 0
489 //   INT64_MAX == d / absl::ZeroDuration()
490 //
491 // The examples involving the `/` operator above also apply to `IDivDuration()`
492 // and `FDivDuration()`.
493 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration InfiniteDuration();
494 
495 // Nanoseconds()
496 // Microseconds()
497 // Milliseconds()
498 // Seconds()
499 // Minutes()
500 // Hours()
501 //
502 // Factory functions for constructing `Duration` values from an integral number
503 // of the unit indicated by the factory function's name. The number must be
504 // representable as int64_t.
505 //
506 // NOTE: no "Days()" factory function exists because "a day" is ambiguous.
507 // Civil days are not always 24 hours long, and a 24-hour duration often does
508 // not correspond with a civil day. If a 24-hour duration is needed, use
509 // `absl::Hours(24)`. If you actually want a civil day, use absl::CivilDay
510 // from civil_time.h.
511 //
512 // Example:
513 //
514 //   absl::Duration a = absl::Seconds(60);
515 //   absl::Duration b = absl::Minutes(1);  // b == a
516 template <typename T, time_internal::EnableIfIntegral<T> = 0>
Nanoseconds(T n)517 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Nanoseconds(T n) {
518   return time_internal::FromInt64(n, std::nano{});
519 }
520 template <typename T, time_internal::EnableIfIntegral<T> = 0>
Microseconds(T n)521 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Microseconds(T n) {
522   return time_internal::FromInt64(n, std::micro{});
523 }
524 template <typename T, time_internal::EnableIfIntegral<T> = 0>
Milliseconds(T n)525 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Milliseconds(T n) {
526   return time_internal::FromInt64(n, std::milli{});
527 }
528 template <typename T, time_internal::EnableIfIntegral<T> = 0>
Seconds(T n)529 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Seconds(T n) {
530   return time_internal::FromInt64(n, std::ratio<1>{});
531 }
532 template <typename T, time_internal::EnableIfIntegral<T> = 0>
Minutes(T n)533 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Minutes(T n) {
534   return time_internal::FromInt64(n, std::ratio<60>{});
535 }
536 template <typename T, time_internal::EnableIfIntegral<T> = 0>
Hours(T n)537 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Hours(T n) {
538   return time_internal::FromInt64(n, std::ratio<3600>{});
539 }
540 
541 // Factory overloads for constructing `Duration` values from a floating-point
542 // number of the unit indicated by the factory function's name. These functions
543 // exist for convenience, but they are not as efficient as the integral
544 // factories, which should be preferred.
545 //
546 // Example:
547 //
548 //   auto a = absl::Seconds(1.5);        // OK
549 //   auto b = absl::Milliseconds(1500);  // BETTER
550 template <typename T, time_internal::EnableIfFloat<T> = 0>
Nanoseconds(T n)551 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Nanoseconds(T n) {
552   return n * Nanoseconds(1);
553 }
554 template <typename T, time_internal::EnableIfFloat<T> = 0>
Microseconds(T n)555 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Microseconds(T n) {
556   return n * Microseconds(1);
557 }
558 template <typename T, time_internal::EnableIfFloat<T> = 0>
Milliseconds(T n)559 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Milliseconds(T n) {
560   return n * Milliseconds(1);
561 }
562 template <typename T, time_internal::EnableIfFloat<T> = 0>
Seconds(T n)563 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Seconds(T n) {
564   if (n >= 0) {  // Note: `NaN >= 0` is false.
565     if (n >= static_cast<T>((std::numeric_limits<int64_t>::max)())) {
566       return InfiniteDuration();
567     }
568     return time_internal::MakePosDoubleDuration(n);
569   } else {
570     if (std::isnan(n))
571       return std::signbit(n) ? -InfiniteDuration() : InfiniteDuration();
572     if (n <= (std::numeric_limits<int64_t>::min)()) return -InfiniteDuration();
573     return -time_internal::MakePosDoubleDuration(-n);
574   }
575 }
576 template <typename T, time_internal::EnableIfFloat<T> = 0>
Minutes(T n)577 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Minutes(T n) {
578   return n * Minutes(1);
579 }
580 template <typename T, time_internal::EnableIfFloat<T> = 0>
Hours(T n)581 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Hours(T n) {
582   return n * Hours(1);
583 }
584 
585 // ToInt64Nanoseconds()
586 // ToInt64Microseconds()
587 // ToInt64Milliseconds()
588 // ToInt64Seconds()
589 // ToInt64Minutes()
590 // ToInt64Hours()
591 //
592 // Helper functions that convert a Duration to an integral count of the
593 // indicated unit. These return the same results as the `IDivDuration()`
594 // function, though they usually do so more efficiently; see the
595 // documentation of `IDivDuration()` for details about overflow, etc.
596 //
597 // Example:
598 //
599 //   absl::Duration d = absl::Milliseconds(1500);
600 //   int64_t isec = absl::ToInt64Seconds(d);  // isec == 1
601 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Nanoseconds(Duration d);
602 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Microseconds(Duration d);
603 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Milliseconds(Duration d);
604 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Seconds(Duration d);
605 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Minutes(Duration d);
606 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Hours(Duration d);
607 
608 // ToDoubleNanoseconds()
609 // ToDoubleMicroseconds()
610 // ToDoubleMilliseconds()
611 // ToDoubleSeconds()
612 // ToDoubleMinutes()
613 // ToDoubleHours()
614 //
615 // Helper functions that convert a Duration to a floating point count of the
616 // indicated unit. These functions are shorthand for the `FDivDuration()`
617 // function above; see its documentation for details about overflow, etc.
618 //
619 // Example:
620 //
621 //   absl::Duration d = absl::Milliseconds(1500);
622 //   double dsec = absl::ToDoubleSeconds(d);  // dsec == 1.5
623 ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleNanoseconds(Duration d);
624 ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMicroseconds(Duration d);
625 ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMilliseconds(Duration d);
626 ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleSeconds(Duration d);
627 ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMinutes(Duration d);
628 ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleHours(Duration d);
629 
630 // FromChrono()
631 //
632 // Converts any of the pre-defined std::chrono durations to an absl::Duration.
633 //
634 // Example:
635 //
636 //   std::chrono::milliseconds ms(123);
637 //   absl::Duration d = absl::FromChrono(ms);
638 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
639     const std::chrono::nanoseconds& d);
640 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
641     const std::chrono::microseconds& d);
642 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
643     const std::chrono::milliseconds& d);
644 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
645     const std::chrono::seconds& d);
646 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
647     const std::chrono::minutes& d);
648 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
649     const std::chrono::hours& d);
650 
651 // ToChronoNanoseconds()
652 // ToChronoMicroseconds()
653 // ToChronoMilliseconds()
654 // ToChronoSeconds()
655 // ToChronoMinutes()
656 // ToChronoHours()
657 //
658 // Converts an absl::Duration to any of the pre-defined std::chrono durations.
659 // If overflow would occur, the returned value will saturate at the min/max
660 // chrono duration value instead.
661 //
662 // Example:
663 //
664 //   absl::Duration d = absl::Microseconds(123);
665 //   auto x = absl::ToChronoMicroseconds(d);
666 //   auto y = absl::ToChronoNanoseconds(d);  // x == y
667 //   auto z = absl::ToChronoSeconds(absl::InfiniteDuration());
668 //   // z == std::chrono::seconds::max()
669 ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::nanoseconds ToChronoNanoseconds(
670     Duration d);
671 ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::microseconds ToChronoMicroseconds(
672     Duration d);
673 ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::milliseconds ToChronoMilliseconds(
674     Duration d);
675 ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::seconds ToChronoSeconds(Duration d);
676 ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::minutes ToChronoMinutes(Duration d);
677 ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::hours ToChronoHours(Duration d);
678 
679 // FormatDuration()
680 //
681 // Returns a string representing the duration in the form "72h3m0.5s".
682 // Returns "inf" or "-inf" for +/- `InfiniteDuration()`.
683 ABSL_ATTRIBUTE_CONST_FUNCTION std::string FormatDuration(Duration d);
684 
685 // Output stream operator.
686 inline std::ostream& operator<<(std::ostream& os, Duration d) {
687   return os << FormatDuration(d);
688 }
689 
690 // Support for StrFormat(), StrCat() etc.
691 template <typename Sink>
AbslStringify(Sink & sink,Duration d)692 void AbslStringify(Sink& sink, Duration d) {
693   sink.Append(FormatDuration(d));
694 }
695 
696 // ParseDuration()
697 //
698 // Parses a duration string consisting of a possibly signed sequence of
699 // decimal numbers, each with an optional fractional part and a unit
700 // suffix.  The valid suffixes are "ns", "us" "ms", "s", "m", and "h".
701 // Simple examples include "300ms", "-1.5h", and "2h45m".  Parses "0" as
702 // `ZeroDuration()`. Parses "inf" and "-inf" as +/- `InfiniteDuration()`.
703 bool ParseDuration(absl::string_view dur_string, Duration* d);
704 
705 // AbslParseFlag()
706 //
707 // Parses a command-line flag string representation `text` into a Duration
708 // value. Duration flags must be specified in a format that is valid input for
709 // `absl::ParseDuration()`.
710 bool AbslParseFlag(absl::string_view text, Duration* dst, std::string* error);
711 
712 
713 // AbslUnparseFlag()
714 //
715 // Unparses a Duration value into a command-line string representation using
716 // the format specified by `absl::ParseDuration()`.
717 std::string AbslUnparseFlag(Duration d);
718 
719 ABSL_DEPRECATED("Use AbslParseFlag() instead.")
720 bool ParseFlag(const std::string& text, Duration* dst, std::string* error);
721 ABSL_DEPRECATED("Use AbslUnparseFlag() instead.")
722 std::string UnparseFlag(Duration d);
723 
724 // Time
725 //
726 // An `absl::Time` represents a specific instant in time. Arithmetic operators
727 // are provided for naturally expressing time calculations. Instances are
728 // created using `absl::Now()` and the `absl::From*()` factory functions that
729 // accept the gamut of other time representations. Formatting and parsing
730 // functions are provided for conversion to and from strings.  `absl::Time`
731 // should be passed by value rather than const reference.
732 //
733 // `absl::Time` assumes there are 60 seconds in a minute, which means the
734 // underlying time scales must be "smeared" to eliminate leap seconds.
735 // See https://developers.google.com/time/smear.
736 //
737 // Even though `absl::Time` supports a wide range of timestamps, exercise
738 // caution when using values in the distant past. `absl::Time` uses the
739 // Proleptic Gregorian calendar, which extends the Gregorian calendar backward
740 // to dates before its introduction in 1582.
741 // See https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar
742 // for more information. Use the ICU calendar classes to convert a date in
743 // some other calendar (http://userguide.icu-project.org/datetime/calendar).
744 //
745 // Similarly, standardized time zones are a reasonably recent innovation, with
746 // the Greenwich prime meridian being established in 1884. The TZ database
747 // itself does not profess accurate offsets for timestamps prior to 1970. The
748 // breakdown of future timestamps is subject to the whim of regional
749 // governments.
750 //
751 // The `absl::Time` class represents an instant in time as a count of clock
752 // ticks of some granularity (resolution) from some starting point (epoch).
753 //
754 // `absl::Time` uses a resolution that is high enough to avoid loss in
755 // precision, and a range that is wide enough to avoid overflow, when
756 // converting between tick counts in most Google time scales (i.e., resolution
757 // of at least one nanosecond, and range +/-100 billion years).  Conversions
758 // between the time scales are performed by truncating (towards negative
759 // infinity) to the nearest representable point.
760 //
761 // Examples:
762 //
763 //   absl::Time t1 = ...;
764 //   absl::Time t2 = t1 + absl::Minutes(2);
765 //   absl::Duration d = t2 - t1;  // == absl::Minutes(2)
766 //
767 class Time {
768  public:
769   // Value semantics.
770 
771   // Returns the Unix epoch.  However, those reading your code may not know
772   // or expect the Unix epoch as the default value, so make your code more
773   // readable by explicitly initializing all instances before use.
774   //
775   // Example:
776   //   absl::Time t = absl::UnixEpoch();
777   //   absl::Time t = absl::Now();
778   //   absl::Time t = absl::TimeFromTimeval(tv);
779   //   absl::Time t = absl::InfinitePast();
780   constexpr Time() = default;
781 
782   // Copyable.
783   constexpr Time(const Time& t) = default;
784   Time& operator=(const Time& t) = default;
785 
786   // Assignment operators.
787   Time& operator+=(Duration d) {
788     rep_ += d;
789     return *this;
790   }
791   Time& operator-=(Duration d) {
792     rep_ -= d;
793     return *this;
794   }
795 
796   // Time::Breakdown
797   //
798   // The calendar and wall-clock (aka "civil time") components of an
799   // `absl::Time` in a certain `absl::TimeZone`. This struct is not
800   // intended to represent an instant in time. So, rather than passing
801   // a `Time::Breakdown` to a function, pass an `absl::Time` and an
802   // `absl::TimeZone`.
803   //
804   // Deprecated. Use `absl::TimeZone::CivilInfo`.
805   struct ABSL_DEPRECATED("Use `absl::TimeZone::CivilInfo`.") Breakdown {
806     int64_t year;        // year (e.g., 2013)
807     int month;           // month of year [1:12]
808     int day;             // day of month [1:31]
809     int hour;            // hour of day [0:23]
810     int minute;          // minute of hour [0:59]
811     int second;          // second of minute [0:59]
812     Duration subsecond;  // [Seconds(0):Seconds(1)) if finite
813     int weekday;         // 1==Mon, ..., 7=Sun
814     int yearday;         // day of year [1:366]
815 
816     // Note: The following fields exist for backward compatibility
817     // with older APIs.  Accessing these fields directly is a sign of
818     // imprudent logic in the calling code.  Modern time-related code
819     // should only access this data indirectly by way of FormatTime().
820     // These fields are undefined for InfiniteFuture() and InfinitePast().
821     int offset;             // seconds east of UTC
822     bool is_dst;            // is offset non-standard?
823     const char* zone_abbr;  // time-zone abbreviation (e.g., "PST")
824   };
825 
826   // Time::In()
827   //
828   // Returns the breakdown of this instant in the given TimeZone.
829   //
830   // Deprecated. Use `absl::TimeZone::At(Time)`.
831   ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING
832   ABSL_DEPRECATED("Use `absl::TimeZone::At(Time)`.")
833   Breakdown In(TimeZone tz) const;
834   ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING
835 
836   template <typename H>
AbslHashValue(H h,Time t)837   friend H AbslHashValue(H h, Time t) {
838     return H::combine(std::move(h), t.rep_);
839   }
840 
841  private:
842   friend constexpr Time time_internal::FromUnixDuration(Duration d);
843   friend constexpr Duration time_internal::ToUnixDuration(Time t);
844   friend constexpr bool operator<(Time lhs, Time rhs);
845   friend constexpr bool operator==(Time lhs, Time rhs);
846   friend Duration operator-(Time lhs, Time rhs);
847   friend constexpr Time UniversalEpoch();
848   friend constexpr Time InfiniteFuture();
849   friend constexpr Time InfinitePast();
Time(Duration rep)850   constexpr explicit Time(Duration rep) : rep_(rep) {}
851   Duration rep_;
852 };
853 
854 // Relational Operators
855 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<(Time lhs, Time rhs) {
856   return lhs.rep_ < rhs.rep_;
857 }
858 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>(Time lhs, Time rhs) {
859   return rhs < lhs;
860 }
861 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>=(Time lhs, Time rhs) {
862   return !(lhs < rhs);
863 }
864 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<=(Time lhs, Time rhs) {
865   return !(rhs < lhs);
866 }
867 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator==(Time lhs, Time rhs) {
868   return lhs.rep_ == rhs.rep_;
869 }
870 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator!=(Time lhs, Time rhs) {
871   return !(lhs == rhs);
872 }
873 
874 // Additive Operators
875 ABSL_ATTRIBUTE_CONST_FUNCTION inline Time operator+(Time lhs, Duration rhs) {
876   return lhs += rhs;
877 }
878 ABSL_ATTRIBUTE_CONST_FUNCTION inline Time operator+(Duration lhs, Time rhs) {
879   return rhs += lhs;
880 }
881 ABSL_ATTRIBUTE_CONST_FUNCTION inline Time operator-(Time lhs, Duration rhs) {
882   return lhs -= rhs;
883 }
884 ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator-(Time lhs, Time rhs) {
885   return lhs.rep_ - rhs.rep_;
886 }
887 
888 // UnixEpoch()
889 //
890 // Returns the `absl::Time` representing "1970-01-01 00:00:00.0 +0000".
UnixEpoch()891 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time UnixEpoch() { return Time(); }
892 
893 // UniversalEpoch()
894 //
895 // Returns the `absl::Time` representing "0001-01-01 00:00:00.0 +0000", the
896 // epoch of the ICU Universal Time Scale.
UniversalEpoch()897 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time UniversalEpoch() {
898   // 719162 is the number of days from 0001-01-01 to 1970-01-01,
899   // assuming the Gregorian calendar.
900   return Time(
901       time_internal::MakeDuration(-24 * 719162 * int64_t{3600}, uint32_t{0}));
902 }
903 
904 // InfiniteFuture()
905 //
906 // Returns an `absl::Time` that is infinitely far in the future.
InfiniteFuture()907 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time InfiniteFuture() {
908   return Time(time_internal::MakeDuration((std::numeric_limits<int64_t>::max)(),
909                                           ~uint32_t{0}));
910 }
911 
912 // InfinitePast()
913 //
914 // Returns an `absl::Time` that is infinitely far in the past.
InfinitePast()915 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time InfinitePast() {
916   return Time(time_internal::MakeDuration((std::numeric_limits<int64_t>::min)(),
917                                           ~uint32_t{0}));
918 }
919 
920 // FromUnixNanos()
921 // FromUnixMicros()
922 // FromUnixMillis()
923 // FromUnixSeconds()
924 // FromTimeT()
925 // FromUDate()
926 // FromUniversal()
927 //
928 // Creates an `absl::Time` from a variety of other representations.  See
929 // https://unicode-org.github.io/icu/userguide/datetime/universaltimescale.html
930 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixNanos(int64_t ns);
931 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixMicros(int64_t us);
932 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixMillis(int64_t ms);
933 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixSeconds(int64_t s);
934 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromTimeT(time_t t);
935 ABSL_ATTRIBUTE_CONST_FUNCTION Time FromUDate(double udate);
936 ABSL_ATTRIBUTE_CONST_FUNCTION Time FromUniversal(int64_t universal);
937 
938 // ToUnixNanos()
939 // ToUnixMicros()
940 // ToUnixMillis()
941 // ToUnixSeconds()
942 // ToTimeT()
943 // ToUDate()
944 // ToUniversal()
945 //
946 // Converts an `absl::Time` to a variety of other representations.  See
947 // https://unicode-org.github.io/icu/userguide/datetime/universaltimescale.html
948 //
949 // Note that these operations round down toward negative infinity where
950 // necessary to adjust to the resolution of the result type.  Beware of
951 // possible time_t over/underflow in ToTime{T,val,spec}() on 32-bit platforms.
952 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixNanos(Time t);
953 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixMicros(Time t);
954 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixMillis(Time t);
955 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixSeconds(Time t);
956 ABSL_ATTRIBUTE_CONST_FUNCTION time_t ToTimeT(Time t);
957 ABSL_ATTRIBUTE_CONST_FUNCTION double ToUDate(Time t);
958 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUniversal(Time t);
959 
960 // DurationFromTimespec()
961 // DurationFromTimeval()
962 // ToTimespec()
963 // ToTimeval()
964 // TimeFromTimespec()
965 // TimeFromTimeval()
966 // ToTimespec()
967 // ToTimeval()
968 //
969 // Some APIs use a timespec or a timeval as a Duration (e.g., nanosleep(2)
970 // and select(2)), while others use them as a Time (e.g. clock_gettime(2)
971 // and gettimeofday(2)), so conversion functions are provided for both cases.
972 // The "to timespec/val" direction is easily handled via overloading, but
973 // for "from timespec/val" the desired type is part of the function name.
974 ABSL_ATTRIBUTE_CONST_FUNCTION Duration DurationFromTimespec(timespec ts);
975 ABSL_ATTRIBUTE_CONST_FUNCTION Duration DurationFromTimeval(timeval tv);
976 ABSL_ATTRIBUTE_CONST_FUNCTION timespec ToTimespec(Duration d);
977 ABSL_ATTRIBUTE_CONST_FUNCTION timeval ToTimeval(Duration d);
978 ABSL_ATTRIBUTE_CONST_FUNCTION Time TimeFromTimespec(timespec ts);
979 ABSL_ATTRIBUTE_CONST_FUNCTION Time TimeFromTimeval(timeval tv);
980 ABSL_ATTRIBUTE_CONST_FUNCTION timespec ToTimespec(Time t);
981 ABSL_ATTRIBUTE_CONST_FUNCTION timeval ToTimeval(Time t);
982 
983 // FromChrono()
984 //
985 // Converts a std::chrono::system_clock::time_point to an absl::Time.
986 //
987 // Example:
988 //
989 //   auto tp = std::chrono::system_clock::from_time_t(123);
990 //   absl::Time t = absl::FromChrono(tp);
991 //   // t == absl::FromTimeT(123)
992 ABSL_ATTRIBUTE_PURE_FUNCTION Time
993 FromChrono(const std::chrono::system_clock::time_point& tp);
994 
995 // ToChronoTime()
996 //
997 // Converts an absl::Time to a std::chrono::system_clock::time_point. If
998 // overflow would occur, the returned value will saturate at the min/max time
999 // point value instead.
1000 //
1001 // Example:
1002 //
1003 //   absl::Time t = absl::FromTimeT(123);
1004 //   auto tp = absl::ToChronoTime(t);
1005 //   // tp == std::chrono::system_clock::from_time_t(123);
1006 ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::system_clock::time_point
1007     ToChronoTime(Time);
1008 
1009 // AbslParseFlag()
1010 //
1011 // Parses the command-line flag string representation `text` into a Time value.
1012 // Time flags must be specified in a format that matches absl::RFC3339_full.
1013 //
1014 // For example:
1015 //
1016 //   --start_time=2016-01-02T03:04:05.678+08:00
1017 //
1018 // Note: A UTC offset (or 'Z' indicating a zero-offset from UTC) is required.
1019 //
1020 // Additionally, if you'd like to specify a time as a count of
1021 // seconds/milliseconds/etc from the Unix epoch, use an absl::Duration flag
1022 // and add that duration to absl::UnixEpoch() to get an absl::Time.
1023 bool AbslParseFlag(absl::string_view text, Time* t, std::string* error);
1024 
1025 // AbslUnparseFlag()
1026 //
1027 // Unparses a Time value into a command-line string representation using
1028 // the format specified by `absl::ParseTime()`.
1029 std::string AbslUnparseFlag(Time t);
1030 
1031 ABSL_DEPRECATED("Use AbslParseFlag() instead.")
1032 bool ParseFlag(const std::string& text, Time* t, std::string* error);
1033 ABSL_DEPRECATED("Use AbslUnparseFlag() instead.")
1034 std::string UnparseFlag(Time t);
1035 
1036 // TimeZone
1037 //
1038 // The `absl::TimeZone` is an opaque, small, value-type class representing a
1039 // geo-political region within which particular rules are used for converting
1040 // between absolute and civil times (see https://git.io/v59Ly). `absl::TimeZone`
1041 // values are named using the TZ identifiers from the IANA Time Zone Database,
1042 // such as "America/Los_Angeles" or "Australia/Sydney". `absl::TimeZone` values
1043 // are created from factory functions such as `absl::LoadTimeZone()`. Note:
1044 // strings like "PST" and "EDT" are not valid TZ identifiers. Prefer to pass by
1045 // value rather than const reference.
1046 //
1047 // For more on the fundamental concepts of time zones, absolute times, and civil
1048 // times, see https://github.com/google/cctz#fundamental-concepts
1049 //
1050 // Examples:
1051 //
1052 //   absl::TimeZone utc = absl::UTCTimeZone();
1053 //   absl::TimeZone pst = absl::FixedTimeZone(-8 * 60 * 60);
1054 //   absl::TimeZone loc = absl::LocalTimeZone();
1055 //   absl::TimeZone lax;
1056 //   if (!absl::LoadTimeZone("America/Los_Angeles", &lax)) {
1057 //     // handle error case
1058 //   }
1059 //
1060 // See also:
1061 // - https://github.com/google/cctz
1062 // - https://www.iana.org/time-zones
1063 // - https://en.wikipedia.org/wiki/Zoneinfo
1064 class TimeZone {
1065  public:
TimeZone(time_internal::cctz::time_zone tz)1066   explicit TimeZone(time_internal::cctz::time_zone tz) : cz_(tz) {}
1067   TimeZone() = default;  // UTC, but prefer UTCTimeZone() to be explicit.
1068 
1069   // Copyable.
1070   TimeZone(const TimeZone&) = default;
1071   TimeZone& operator=(const TimeZone&) = default;
1072 
time_zone()1073   explicit operator time_internal::cctz::time_zone() const { return cz_; }
1074 
name()1075   std::string name() const { return cz_.name(); }
1076 
1077   // TimeZone::CivilInfo
1078   //
1079   // Information about the civil time corresponding to an absolute time.
1080   // This struct is not intended to represent an instant in time. So, rather
1081   // than passing a `TimeZone::CivilInfo` to a function, pass an `absl::Time`
1082   // and an `absl::TimeZone`.
1083   struct CivilInfo {
1084     CivilSecond cs;
1085     Duration subsecond;
1086 
1087     // Note: The following fields exist for backward compatibility
1088     // with older APIs.  Accessing these fields directly is a sign of
1089     // imprudent logic in the calling code.  Modern time-related code
1090     // should only access this data indirectly by way of FormatTime().
1091     // These fields are undefined for InfiniteFuture() and InfinitePast().
1092     int offset;             // seconds east of UTC
1093     bool is_dst;            // is offset non-standard?
1094     const char* zone_abbr;  // time-zone abbreviation (e.g., "PST")
1095   };
1096 
1097   // TimeZone::At(Time)
1098   //
1099   // Returns the civil time for this TimeZone at a certain `absl::Time`.
1100   // If the input time is infinite, the output civil second will be set to
1101   // CivilSecond::max() or min(), and the subsecond will be infinite.
1102   //
1103   // Example:
1104   //
1105   //   const auto epoch = lax.At(absl::UnixEpoch());
1106   //   // epoch.cs == 1969-12-31 16:00:00
1107   //   // epoch.subsecond == absl::ZeroDuration()
1108   //   // epoch.offset == -28800
1109   //   // epoch.is_dst == false
1110   //   // epoch.abbr == "PST"
1111   CivilInfo At(Time t) const;
1112 
1113   // TimeZone::TimeInfo
1114   //
1115   // Information about the absolute times corresponding to a civil time.
1116   // (Subseconds must be handled separately.)
1117   //
1118   // It is possible for a caller to pass a civil-time value that does
1119   // not represent an actual or unique instant in time (due to a shift
1120   // in UTC offset in the TimeZone, which results in a discontinuity in
1121   // the civil-time components). For example, a daylight-saving-time
1122   // transition skips or repeats civil times---in the United States,
1123   // March 13, 2011 02:15 never occurred, while November 6, 2011 01:15
1124   // occurred twice---so requests for such times are not well-defined.
1125   // To account for these possibilities, `absl::TimeZone::TimeInfo` is
1126   // richer than just a single `absl::Time`.
1127   struct TimeInfo {
1128     enum CivilKind {
1129       UNIQUE,    // the civil time was singular (pre == trans == post)
1130       SKIPPED,   // the civil time did not exist (pre >= trans > post)
1131       REPEATED,  // the civil time was ambiguous (pre < trans <= post)
1132     } kind;
1133     Time pre;    // time calculated using the pre-transition offset
1134     Time trans;  // when the civil-time discontinuity occurred
1135     Time post;   // time calculated using the post-transition offset
1136   };
1137 
1138   // TimeZone::At(CivilSecond)
1139   //
1140   // Returns an `absl::TimeInfo` containing the absolute time(s) for this
1141   // TimeZone at an `absl::CivilSecond`. When the civil time is skipped or
1142   // repeated, returns times calculated using the pre-transition and post-
1143   // transition UTC offsets, plus the transition time itself.
1144   //
1145   // Examples:
1146   //
1147   //   // A unique civil time
1148   //   const auto jan01 = lax.At(absl::CivilSecond(2011, 1, 1, 0, 0, 0));
1149   //   // jan01.kind == TimeZone::TimeInfo::UNIQUE
1150   //   // jan01.pre    is 2011-01-01 00:00:00 -0800
1151   //   // jan01.trans  is 2011-01-01 00:00:00 -0800
1152   //   // jan01.post   is 2011-01-01 00:00:00 -0800
1153   //
1154   //   // A Spring DST transition, when there is a gap in civil time
1155   //   const auto mar13 = lax.At(absl::CivilSecond(2011, 3, 13, 2, 15, 0));
1156   //   // mar13.kind == TimeZone::TimeInfo::SKIPPED
1157   //   // mar13.pre   is 2011-03-13 03:15:00 -0700
1158   //   // mar13.trans is 2011-03-13 03:00:00 -0700
1159   //   // mar13.post  is 2011-03-13 01:15:00 -0800
1160   //
1161   //   // A Fall DST transition, when civil times are repeated
1162   //   const auto nov06 = lax.At(absl::CivilSecond(2011, 11, 6, 1, 15, 0));
1163   //   // nov06.kind == TimeZone::TimeInfo::REPEATED
1164   //   // nov06.pre   is 2011-11-06 01:15:00 -0700
1165   //   // nov06.trans is 2011-11-06 01:00:00 -0800
1166   //   // nov06.post  is 2011-11-06 01:15:00 -0800
1167   TimeInfo At(CivilSecond ct) const;
1168 
1169   // TimeZone::NextTransition()
1170   // TimeZone::PrevTransition()
1171   //
1172   // Finds the time of the next/previous offset change in this time zone.
1173   //
1174   // By definition, `NextTransition(t, &trans)` returns false when `t` is
1175   // `InfiniteFuture()`, and `PrevTransition(t, &trans)` returns false
1176   // when `t` is `InfinitePast()`. If the zone has no transitions, the
1177   // result will also be false no matter what the argument.
1178   //
1179   // Otherwise, when `t` is `InfinitePast()`, `NextTransition(t, &trans)`
1180   // returns true and sets `trans` to the first recorded transition. Chains
1181   // of calls to `NextTransition()/PrevTransition()` will eventually return
1182   // false, but it is unspecified exactly when `NextTransition(t, &trans)`
1183   // jumps to false, or what time is set by `PrevTransition(t, &trans)` for
1184   // a very distant `t`.
1185   //
1186   // Note: Enumeration of time-zone transitions is for informational purposes
1187   // only. Modern time-related code should not care about when offset changes
1188   // occur.
1189   //
1190   // Example:
1191   //   absl::TimeZone nyc;
1192   //   if (!absl::LoadTimeZone("America/New_York", &nyc)) { ... }
1193   //   const auto now = absl::Now();
1194   //   auto t = absl::InfinitePast();
1195   //   absl::TimeZone::CivilTransition trans;
1196   //   while (t <= now && nyc.NextTransition(t, &trans)) {
1197   //     // transition: trans.from -> trans.to
1198   //     t = nyc.At(trans.to).trans;
1199   //   }
1200   struct CivilTransition {
1201     CivilSecond from;  // the civil time we jump from
1202     CivilSecond to;    // the civil time we jump to
1203   };
1204   bool NextTransition(Time t, CivilTransition* trans) const;
1205   bool PrevTransition(Time t, CivilTransition* trans) const;
1206 
1207   template <typename H>
AbslHashValue(H h,TimeZone tz)1208   friend H AbslHashValue(H h, TimeZone tz) {
1209     return H::combine(std::move(h), tz.cz_);
1210   }
1211 
1212  private:
1213   friend bool operator==(TimeZone a, TimeZone b) { return a.cz_ == b.cz_; }
1214   friend bool operator!=(TimeZone a, TimeZone b) { return a.cz_ != b.cz_; }
1215   friend std::ostream& operator<<(std::ostream& os, TimeZone tz) {
1216     return os << tz.name();
1217   }
1218 
1219   time_internal::cctz::time_zone cz_;
1220 };
1221 
1222 // LoadTimeZone()
1223 //
1224 // Loads the named zone. May perform I/O on the initial load of the named
1225 // zone. If the name is invalid, or some other kind of error occurs, returns
1226 // `false` and `*tz` is set to the UTC time zone.
LoadTimeZone(absl::string_view name,TimeZone * tz)1227 inline bool LoadTimeZone(absl::string_view name, TimeZone* tz) {
1228   if (name == "localtime") {
1229     *tz = TimeZone(time_internal::cctz::local_time_zone());
1230     return true;
1231   }
1232   time_internal::cctz::time_zone cz;
1233   const bool b = time_internal::cctz::load_time_zone(std::string(name), &cz);
1234   *tz = TimeZone(cz);
1235   return b;
1236 }
1237 
1238 // FixedTimeZone()
1239 //
1240 // Returns a TimeZone that is a fixed offset (seconds east) from UTC.
1241 // Note: If the absolute value of the offset is greater than 24 hours
1242 // you'll get UTC (i.e., no offset) instead.
FixedTimeZone(int seconds)1243 inline TimeZone FixedTimeZone(int seconds) {
1244   return TimeZone(
1245       time_internal::cctz::fixed_time_zone(std::chrono::seconds(seconds)));
1246 }
1247 
1248 // UTCTimeZone()
1249 //
1250 // Convenience method returning the UTC time zone.
UTCTimeZone()1251 inline TimeZone UTCTimeZone() {
1252   return TimeZone(time_internal::cctz::utc_time_zone());
1253 }
1254 
1255 // LocalTimeZone()
1256 //
1257 // Convenience method returning the local time zone, or UTC if there is
1258 // no configured local zone.  Warning: Be wary of using LocalTimeZone(),
1259 // and particularly so in a server process, as the zone configured for the
1260 // local machine should be irrelevant.  Prefer an explicit zone name.
LocalTimeZone()1261 inline TimeZone LocalTimeZone() {
1262   return TimeZone(time_internal::cctz::local_time_zone());
1263 }
1264 
1265 // ToCivilSecond()
1266 // ToCivilMinute()
1267 // ToCivilHour()
1268 // ToCivilDay()
1269 // ToCivilMonth()
1270 // ToCivilYear()
1271 //
1272 // Helpers for TimeZone::At(Time) to return particularly aligned civil times.
1273 //
1274 // Example:
1275 //
1276 //   absl::Time t = ...;
1277 //   absl::TimeZone tz = ...;
1278 //   const auto cd = absl::ToCivilDay(t, tz);
ToCivilSecond(Time t,TimeZone tz)1279 ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilSecond ToCivilSecond(Time t,
1280                                                               TimeZone tz) {
1281   return tz.At(t).cs;  // already a CivilSecond
1282 }
ToCivilMinute(Time t,TimeZone tz)1283 ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilMinute ToCivilMinute(Time t,
1284                                                               TimeZone tz) {
1285   return CivilMinute(tz.At(t).cs);
1286 }
ToCivilHour(Time t,TimeZone tz)1287 ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilHour ToCivilHour(Time t, TimeZone tz) {
1288   return CivilHour(tz.At(t).cs);
1289 }
ToCivilDay(Time t,TimeZone tz)1290 ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilDay ToCivilDay(Time t, TimeZone tz) {
1291   return CivilDay(tz.At(t).cs);
1292 }
ToCivilMonth(Time t,TimeZone tz)1293 ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilMonth ToCivilMonth(Time t,
1294                                                             TimeZone tz) {
1295   return CivilMonth(tz.At(t).cs);
1296 }
ToCivilYear(Time t,TimeZone tz)1297 ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilYear ToCivilYear(Time t, TimeZone tz) {
1298   return CivilYear(tz.At(t).cs);
1299 }
1300 
1301 // FromCivil()
1302 //
1303 // Helper for TimeZone::At(CivilSecond) that provides "order-preserving
1304 // semantics." If the civil time maps to a unique time, that time is
1305 // returned. If the civil time is repeated in the given time zone, the
1306 // time using the pre-transition offset is returned. Otherwise, the
1307 // civil time is skipped in the given time zone, and the transition time
1308 // is returned. This means that for any two civil times, ct1 and ct2,
1309 // (ct1 < ct2) => (FromCivil(ct1) <= FromCivil(ct2)), the equal case
1310 // being when two non-existent civil times map to the same transition time.
1311 //
1312 // Note: Accepts civil times of any alignment.
FromCivil(CivilSecond ct,TimeZone tz)1313 ABSL_ATTRIBUTE_PURE_FUNCTION inline Time FromCivil(CivilSecond ct,
1314                                                    TimeZone tz) {
1315   const auto ti = tz.At(ct);
1316   if (ti.kind == TimeZone::TimeInfo::SKIPPED) return ti.trans;
1317   return ti.pre;
1318 }
1319 
1320 // TimeConversion
1321 //
1322 // An `absl::TimeConversion` represents the conversion of year, month, day,
1323 // hour, minute, and second values (i.e., a civil time), in a particular
1324 // `absl::TimeZone`, to a time instant (an absolute time), as returned by
1325 // `absl::ConvertDateTime()`. Legacy version of `absl::TimeZone::TimeInfo`.
1326 //
1327 // Deprecated. Use `absl::TimeZone::TimeInfo`.
1328 struct ABSL_DEPRECATED("Use `absl::TimeZone::TimeInfo`.") TimeConversion {
1329   Time pre;    // time calculated using the pre-transition offset
1330   Time trans;  // when the civil-time discontinuity occurred
1331   Time post;   // time calculated using the post-transition offset
1332 
1333   enum Kind {
1334     UNIQUE,    // the civil time was singular (pre == trans == post)
1335     SKIPPED,   // the civil time did not exist
1336     REPEATED,  // the civil time was ambiguous
1337   };
1338   Kind kind;
1339 
1340   bool normalized;  // input values were outside their valid ranges
1341 };
1342 
1343 // ConvertDateTime()
1344 //
1345 // Legacy version of `absl::TimeZone::At(absl::CivilSecond)` that takes
1346 // the civil time as six, separate values (YMDHMS).
1347 //
1348 // The input month, day, hour, minute, and second values can be outside
1349 // of their valid ranges, in which case they will be "normalized" during
1350 // the conversion.
1351 //
1352 // Example:
1353 //
1354 //   // "October 32" normalizes to "November 1".
1355 //   absl::TimeConversion tc =
1356 //       absl::ConvertDateTime(2013, 10, 32, 8, 30, 0, lax);
1357 //   // tc.kind == TimeConversion::UNIQUE && tc.normalized == true
1358 //   // absl::ToCivilDay(tc.pre, tz).month() == 11
1359 //   // absl::ToCivilDay(tc.pre, tz).day() == 1
1360 //
1361 // Deprecated. Use `absl::TimeZone::At(CivilSecond)`.
1362 ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING
1363 ABSL_DEPRECATED("Use `absl::TimeZone::At(CivilSecond)`.")
1364 TimeConversion ConvertDateTime(int64_t year, int mon, int day, int hour,
1365                                int min, int sec, TimeZone tz);
1366 ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING
1367 
1368 // FromDateTime()
1369 //
1370 // A convenience wrapper for `absl::ConvertDateTime()` that simply returns
1371 // the "pre" `absl::Time`.  That is, the unique result, or the instant that
1372 // is correct using the pre-transition offset (as if the transition never
1373 // happened).
1374 //
1375 // Example:
1376 //
1377 //   absl::Time t = absl::FromDateTime(2017, 9, 26, 9, 30, 0, lax);
1378 //   // t = 2017-09-26 09:30:00 -0700
1379 //
1380 // Deprecated. Use `absl::FromCivil(CivilSecond, TimeZone)`. Note that the
1381 // behavior of `FromCivil()` differs from `FromDateTime()` for skipped civil
1382 // times. If you care about that see `absl::TimeZone::At(absl::CivilSecond)`.
1383 ABSL_DEPRECATED("Use `absl::FromCivil(CivilSecond, TimeZone)`.")
FromDateTime(int64_t year,int mon,int day,int hour,int min,int sec,TimeZone tz)1384 inline Time FromDateTime(int64_t year, int mon, int day, int hour, int min,
1385                          int sec, TimeZone tz) {
1386   ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING
1387   return ConvertDateTime(year, mon, day, hour, min, sec, tz).pre;
1388   ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING
1389 }
1390 
1391 // FromTM()
1392 //
1393 // Converts the `tm_year`, `tm_mon`, `tm_mday`, `tm_hour`, `tm_min`, and
1394 // `tm_sec` fields to an `absl::Time` using the given time zone. See ctime(3)
1395 // for a description of the expected values of the tm fields. If the civil time
1396 // is unique (see `absl::TimeZone::At(absl::CivilSecond)` above), the matching
1397 // time instant is returned.  Otherwise, the `tm_isdst` field is consulted to
1398 // choose between the possible results.  For a repeated civil time, `tm_isdst !=
1399 // 0` returns the matching DST instant, while `tm_isdst == 0` returns the
1400 // matching non-DST instant.  For a skipped civil time there is no matching
1401 // instant, so `tm_isdst != 0` returns the DST instant, and `tm_isdst == 0`
1402 // returns the non-DST instant, that would have matched if the transition never
1403 // happened.
1404 ABSL_ATTRIBUTE_PURE_FUNCTION Time FromTM(const struct tm& tm, TimeZone tz);
1405 
1406 // ToTM()
1407 //
1408 // Converts the given `absl::Time` to a struct tm using the given time zone.
1409 // See ctime(3) for a description of the values of the tm fields.
1410 ABSL_ATTRIBUTE_PURE_FUNCTION struct tm ToTM(Time t, TimeZone tz);
1411 
1412 // RFC3339_full
1413 // RFC3339_sec
1414 //
1415 // FormatTime()/ParseTime() format specifiers for RFC3339 date/time strings,
1416 // with trailing zeros trimmed or with fractional seconds omitted altogether.
1417 //
1418 // Note that RFC3339_sec[] matches an ISO 8601 extended format for date and
1419 // time with UTC offset.  Also note the use of "%Y": RFC3339 mandates that
1420 // years have exactly four digits, but we allow them to take their natural
1421 // width.
1422 ABSL_DLL extern const char RFC3339_full[];  // %Y-%m-%d%ET%H:%M:%E*S%Ez
1423 ABSL_DLL extern const char RFC3339_sec[];   // %Y-%m-%d%ET%H:%M:%S%Ez
1424 
1425 // RFC1123_full
1426 // RFC1123_no_wday
1427 //
1428 // FormatTime()/ParseTime() format specifiers for RFC1123 date/time strings.
1429 ABSL_DLL extern const char RFC1123_full[];     // %a, %d %b %E4Y %H:%M:%S %z
1430 ABSL_DLL extern const char RFC1123_no_wday[];  // %d %b %E4Y %H:%M:%S %z
1431 
1432 // FormatTime()
1433 //
1434 // Formats the given `absl::Time` in the `absl::TimeZone` according to the
1435 // provided format string. Uses strftime()-like formatting options, with
1436 // the following extensions:
1437 //
1438 //   - %Ez  - RFC3339-compatible numeric UTC offset (+hh:mm or -hh:mm)
1439 //   - %E*z - Full-resolution numeric UTC offset (+hh:mm:ss or -hh:mm:ss)
1440 //   - %E#S - Seconds with # digits of fractional precision
1441 //   - %E*S - Seconds with full fractional precision (a literal '*')
1442 //   - %E#f - Fractional seconds with # digits of precision
1443 //   - %E*f - Fractional seconds with full precision (a literal '*')
1444 //   - %E4Y - Four-character years (-999 ... -001, 0000, 0001 ... 9999)
1445 //   - %ET  - The RFC3339 "date-time" separator "T"
1446 //
1447 // Note that %E0S behaves like %S, and %E0f produces no characters.  In
1448 // contrast %E*f always produces at least one digit, which may be '0'.
1449 //
1450 // Note that %Y produces as many characters as it takes to fully render the
1451 // year.  A year outside of [-999:9999] when formatted with %E4Y will produce
1452 // more than four characters, just like %Y.
1453 //
1454 // We recommend that format strings include the UTC offset (%z, %Ez, or %E*z)
1455 // so that the result uniquely identifies a time instant.
1456 //
1457 // Example:
1458 //
1459 //   absl::CivilSecond cs(2013, 1, 2, 3, 4, 5);
1460 //   absl::Time t = absl::FromCivil(cs, lax);
1461 //   std::string f = absl::FormatTime("%H:%M:%S", t, lax);  // "03:04:05"
1462 //   f = absl::FormatTime("%H:%M:%E3S", t, lax);  // "03:04:05.000"
1463 //
1464 // Note: If the given `absl::Time` is `absl::InfiniteFuture()`, the returned
1465 // string will be exactly "infinite-future". If the given `absl::Time` is
1466 // `absl::InfinitePast()`, the returned string will be exactly "infinite-past".
1467 // In both cases the given format string and `absl::TimeZone` are ignored.
1468 //
1469 ABSL_ATTRIBUTE_PURE_FUNCTION std::string FormatTime(absl::string_view format,
1470                                                     Time t, TimeZone tz);
1471 
1472 // Convenience functions that format the given time using the RFC3339_full
1473 // format.  The first overload uses the provided TimeZone, while the second
1474 // uses LocalTimeZone().
1475 ABSL_ATTRIBUTE_PURE_FUNCTION std::string FormatTime(Time t, TimeZone tz);
1476 ABSL_ATTRIBUTE_PURE_FUNCTION std::string FormatTime(Time t);
1477 
1478 // Output stream operator.
1479 inline std::ostream& operator<<(std::ostream& os, Time t) {
1480   return os << FormatTime(t);
1481 }
1482 
1483 // Support for StrFormat(), StrCat() etc.
1484 template <typename Sink>
AbslStringify(Sink & sink,Time t)1485 void AbslStringify(Sink& sink, Time t) {
1486   sink.Append(FormatTime(t));
1487 }
1488 
1489 // ParseTime()
1490 //
1491 // Parses an input string according to the provided format string and
1492 // returns the corresponding `absl::Time`. Uses strftime()-like formatting
1493 // options, with the same extensions as FormatTime(), but with the
1494 // exceptions that %E#S is interpreted as %E*S, and %E#f as %E*f.  %Ez
1495 // and %E*z also accept the same inputs, which (along with %z) includes
1496 // 'z' and 'Z' as synonyms for +00:00.  %ET accepts either 'T' or 't'.
1497 //
1498 // %Y consumes as many numeric characters as it can, so the matching data
1499 // should always be terminated with a non-numeric.  %E4Y always consumes
1500 // exactly four characters, including any sign.
1501 //
1502 // Unspecified fields are taken from the default date and time of ...
1503 //
1504 //   "1970-01-01 00:00:00.0 +0000"
1505 //
1506 // For example, parsing a string of "15:45" (%H:%M) will return an absl::Time
1507 // that represents "1970-01-01 15:45:00.0 +0000".
1508 //
1509 // Note that since ParseTime() returns time instants, it makes the most sense
1510 // to parse fully-specified date/time strings that include a UTC offset (%z,
1511 // %Ez, or %E*z).
1512 //
1513 // Note also that `absl::ParseTime()` only heeds the fields year, month, day,
1514 // hour, minute, (fractional) second, and UTC offset.  Other fields, like
1515 // weekday (%a or %A), while parsed for syntactic validity, are ignored
1516 // in the conversion.
1517 //
1518 // Date and time fields that are out-of-range will be treated as errors
1519 // rather than normalizing them like `absl::CivilSecond` does.  For example,
1520 // it is an error to parse the date "Oct 32, 2013" because 32 is out of range.
1521 //
1522 // A leap second of ":60" is normalized to ":00" of the following minute
1523 // with fractional seconds discarded.  The following table shows how the
1524 // given seconds and subseconds will be parsed:
1525 //
1526 //   "59.x" -> 59.x  // exact
1527 //   "60.x" -> 00.0  // normalized
1528 //   "00.x" -> 00.x  // exact
1529 //
1530 // Errors are indicated by returning false and assigning an error message
1531 // to the "err" out param if it is non-null.
1532 //
1533 // Note: If the input string is exactly "infinite-future", the returned
1534 // `absl::Time` will be `absl::InfiniteFuture()` and `true` will be returned.
1535 // If the input string is "infinite-past", the returned `absl::Time` will be
1536 // `absl::InfinitePast()` and `true` will be returned.
1537 //
1538 bool ParseTime(absl::string_view format, absl::string_view input, Time* time,
1539                std::string* err);
1540 
1541 // Like ParseTime() above, but if the format string does not contain a UTC
1542 // offset specification (%z/%Ez/%E*z) then the input is interpreted in the
1543 // given TimeZone.  This means that the input, by itself, does not identify a
1544 // unique instant.  Being time-zone dependent, it also admits the possibility
1545 // of ambiguity or non-existence, in which case the "pre" time (as defined
1546 // by TimeZone::TimeInfo) is returned.  For these reasons we recommend that
1547 // all date/time strings include a UTC offset so they're context independent.
1548 bool ParseTime(absl::string_view format, absl::string_view input, TimeZone tz,
1549                Time* time, std::string* err);
1550 
1551 // ============================================================================
1552 // Implementation Details Follow
1553 // ============================================================================
1554 
1555 namespace time_internal {
1556 
1557 // Creates a Duration with a given representation.
1558 // REQUIRES: hi,lo is a valid representation of a Duration as specified
1559 // in time/duration.cc.
1560 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeDuration(int64_t hi,
1561                                                               uint32_t lo = 0) {
1562   return Duration(hi, lo);
1563 }
1564 
MakeDuration(int64_t hi,int64_t lo)1565 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeDuration(int64_t hi,
1566                                                               int64_t lo) {
1567   return MakeDuration(hi, static_cast<uint32_t>(lo));
1568 }
1569 
1570 // Make a Duration value from a floating-point number, as long as that number
1571 // is in the range [ 0 .. numeric_limits<int64_t>::max ), that is, as long as
1572 // it's positive and can be converted to int64_t without risk of UB.
MakePosDoubleDuration(double n)1573 ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration MakePosDoubleDuration(double n) {
1574   const int64_t int_secs = static_cast<int64_t>(n);
1575   const uint32_t ticks = static_cast<uint32_t>(
1576       std::round((n - static_cast<double>(int_secs)) * kTicksPerSecond));
1577   return ticks < kTicksPerSecond
1578              ? MakeDuration(int_secs, ticks)
1579              : MakeDuration(int_secs + 1, ticks - kTicksPerSecond);
1580 }
1581 
1582 // Creates a normalized Duration from an almost-normalized (sec,ticks)
1583 // pair. sec may be positive or negative.  ticks must be in the range
1584 // -kTicksPerSecond < *ticks < kTicksPerSecond.  If ticks is negative it
1585 // will be normalized to a positive value in the resulting Duration.
MakeNormalizedDuration(int64_t sec,int64_t ticks)1586 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeNormalizedDuration(
1587     int64_t sec, int64_t ticks) {
1588   return (ticks < 0) ? MakeDuration(sec - 1, ticks + kTicksPerSecond)
1589                      : MakeDuration(sec, ticks);
1590 }
1591 
1592 // Provide access to the Duration representation.
GetRepHi(Duration d)1593 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t GetRepHi(Duration d) {
1594   return d.rep_hi_.Get();
1595 }
GetRepLo(Duration d)1596 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr uint32_t GetRepLo(Duration d) {
1597   return d.rep_lo_;
1598 }
1599 
1600 // Returns true iff d is positive or negative infinity.
IsInfiniteDuration(Duration d)1601 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool IsInfiniteDuration(Duration d) {
1602   return GetRepLo(d) == ~uint32_t{0};
1603 }
1604 
1605 // Returns an infinite Duration with the opposite sign.
1606 // REQUIRES: IsInfiniteDuration(d)
OppositeInfinity(Duration d)1607 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration OppositeInfinity(Duration d) {
1608   return GetRepHi(d) < 0
1609              ? MakeDuration((std::numeric_limits<int64_t>::max)(), ~uint32_t{0})
1610              : MakeDuration((std::numeric_limits<int64_t>::min)(),
1611                             ~uint32_t{0});
1612 }
1613 
1614 // Returns (-n)-1 (equivalently -(n+1)) without avoidable overflow.
NegateAndSubtractOne(int64_t n)1615 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t NegateAndSubtractOne(
1616     int64_t n) {
1617   // Note: Good compilers will optimize this expression to ~n when using
1618   // a two's-complement representation (which is required for int64_t).
1619   return (n < 0) ? -(n + 1) : (-n) - 1;
1620 }
1621 
1622 // Map between a Time and a Duration since the Unix epoch.  Note that these
1623 // functions depend on the above mentioned choice of the Unix epoch for the
1624 // Time representation (and both need to be Time friends).  Without this
1625 // knowledge, we would need to add-in/subtract-out UnixEpoch() respectively.
FromUnixDuration(Duration d)1626 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixDuration(Duration d) {
1627   return Time(d);
1628 }
ToUnixDuration(Time t)1629 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration ToUnixDuration(Time t) {
1630   return t.rep_;
1631 }
1632 
1633 template <std::intmax_t N>
FromInt64(int64_t v,std::ratio<1,N>)1634 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
1635                                                            std::ratio<1, N>) {
1636   static_assert(0 < N && N <= 1000 * 1000 * 1000, "Unsupported ratio");
1637   // Subsecond ratios cannot overflow.
1638   return MakeNormalizedDuration(
1639       v / N, v % N * kTicksPerNanosecond * 1000 * 1000 * 1000 / N);
1640 }
FromInt64(int64_t v,std::ratio<60>)1641 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
1642                                                            std::ratio<60>) {
1643   return (v <= (std::numeric_limits<int64_t>::max)() / 60 &&
1644           v >= (std::numeric_limits<int64_t>::min)() / 60)
1645              ? MakeDuration(v * 60)
1646              : v > 0 ? InfiniteDuration() : -InfiniteDuration();
1647 }
FromInt64(int64_t v,std::ratio<3600>)1648 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
1649                                                            std::ratio<3600>) {
1650   return (v <= (std::numeric_limits<int64_t>::max)() / 3600 &&
1651           v >= (std::numeric_limits<int64_t>::min)() / 3600)
1652              ? MakeDuration(v * 3600)
1653              : v > 0 ? InfiniteDuration() : -InfiniteDuration();
1654 }
1655 
1656 // IsValidRep64<T>(0) is true if the expression `int64_t{std::declval<T>()}` is
1657 // valid. That is, if a T can be assigned to an int64_t without narrowing.
1658 template <typename T>
1659 constexpr auto IsValidRep64(int) -> decltype(int64_t{std::declval<T>()} == 0) {
1660   return true;
1661 }
1662 template <typename T>
1663 constexpr auto IsValidRep64(char) -> bool {
1664   return false;
1665 }
1666 
1667 // Converts a std::chrono::duration to an absl::Duration.
1668 template <typename Rep, typename Period>
FromChrono(const std::chrono::duration<Rep,Period> & d)1669 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1670     const std::chrono::duration<Rep, Period>& d) {
1671   static_assert(IsValidRep64<Rep>(0), "duration::rep is invalid");
1672   return FromInt64(int64_t{d.count()}, Period{});
1673 }
1674 
1675 template <typename Ratio>
ToInt64(Duration d,Ratio)1676 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64(Duration d, Ratio) {
1677   // Note: This may be used on MSVC, which may have a system_clock period of
1678   // std::ratio<1, 10 * 1000 * 1000>
1679   return ToInt64Seconds(d * Ratio::den / Ratio::num);
1680 }
1681 // Fastpath implementations for the 6 common duration units.
ToInt64(Duration d,std::nano)1682 ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d, std::nano) {
1683   return ToInt64Nanoseconds(d);
1684 }
ToInt64(Duration d,std::micro)1685 ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d, std::micro) {
1686   return ToInt64Microseconds(d);
1687 }
ToInt64(Duration d,std::milli)1688 ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d, std::milli) {
1689   return ToInt64Milliseconds(d);
1690 }
ToInt64(Duration d,std::ratio<1>)1691 ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d,
1692                                                      std::ratio<1>) {
1693   return ToInt64Seconds(d);
1694 }
ToInt64(Duration d,std::ratio<60>)1695 ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d,
1696                                                      std::ratio<60>) {
1697   return ToInt64Minutes(d);
1698 }
ToInt64(Duration d,std::ratio<3600>)1699 ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d,
1700                                                      std::ratio<3600>) {
1701   return ToInt64Hours(d);
1702 }
1703 
1704 // Converts an absl::Duration to a chrono duration of type T.
1705 template <typename T>
ToChronoDuration(Duration d)1706 ABSL_ATTRIBUTE_CONST_FUNCTION T ToChronoDuration(Duration d) {
1707   using Rep = typename T::rep;
1708   using Period = typename T::period;
1709   static_assert(IsValidRep64<Rep>(0), "duration::rep is invalid");
1710   if (time_internal::IsInfiniteDuration(d))
1711     return d < ZeroDuration() ? (T::min)() : (T::max)();
1712   const auto v = ToInt64(d, Period{});
1713   if (v > (std::numeric_limits<Rep>::max)()) return (T::max)();
1714   if (v < (std::numeric_limits<Rep>::min)()) return (T::min)();
1715   return T{v};
1716 }
1717 
1718 }  // namespace time_internal
1719 
1720 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<(Duration lhs,
1721                                                        Duration rhs) {
1722   return time_internal::GetRepHi(lhs) != time_internal::GetRepHi(rhs)
1723              ? time_internal::GetRepHi(lhs) < time_internal::GetRepHi(rhs)
1724          : time_internal::GetRepHi(lhs) == (std::numeric_limits<int64_t>::min)()
1725              ? time_internal::GetRepLo(lhs) + 1 <
1726                    time_internal::GetRepLo(rhs) + 1
1727              : time_internal::GetRepLo(lhs) < time_internal::GetRepLo(rhs);
1728 }
1729 
1730 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator==(Duration lhs,
1731                                                         Duration rhs) {
1732   return time_internal::GetRepHi(lhs) == time_internal::GetRepHi(rhs) &&
1733          time_internal::GetRepLo(lhs) == time_internal::GetRepLo(rhs);
1734 }
1735 
1736 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration operator-(Duration d) {
1737   // This is a little interesting because of the special cases.
1738   //
1739   // If rep_lo_ is zero, we have it easy; it's safe to negate rep_hi_, we're
1740   // dealing with an integral number of seconds, and the only special case is
1741   // the maximum negative finite duration, which can't be negated.
1742   //
1743   // Infinities stay infinite, and just change direction.
1744   //
1745   // Finally we're in the case where rep_lo_ is non-zero, and we can borrow
1746   // a second's worth of ticks and avoid overflow (as negating int64_t-min + 1
1747   // is safe).
1748   return time_internal::GetRepLo(d) == 0
1749              ? time_internal::GetRepHi(d) ==
1750                        (std::numeric_limits<int64_t>::min)()
1751                    ? InfiniteDuration()
1752                    : time_internal::MakeDuration(-time_internal::GetRepHi(d))
1753              : time_internal::IsInfiniteDuration(d)
1754                    ? time_internal::OppositeInfinity(d)
1755                    : time_internal::MakeDuration(
1756                          time_internal::NegateAndSubtractOne(
1757                              time_internal::GetRepHi(d)),
1758                          time_internal::kTicksPerSecond -
1759                              time_internal::GetRepLo(d));
1760 }
1761 
InfiniteDuration()1762 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration InfiniteDuration() {
1763   return time_internal::MakeDuration((std::numeric_limits<int64_t>::max)(),
1764                                      ~uint32_t{0});
1765 }
1766 
FromChrono(const std::chrono::nanoseconds & d)1767 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1768     const std::chrono::nanoseconds& d) {
1769   return time_internal::FromChrono(d);
1770 }
FromChrono(const std::chrono::microseconds & d)1771 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1772     const std::chrono::microseconds& d) {
1773   return time_internal::FromChrono(d);
1774 }
FromChrono(const std::chrono::milliseconds & d)1775 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1776     const std::chrono::milliseconds& d) {
1777   return time_internal::FromChrono(d);
1778 }
FromChrono(const std::chrono::seconds & d)1779 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1780     const std::chrono::seconds& d) {
1781   return time_internal::FromChrono(d);
1782 }
FromChrono(const std::chrono::minutes & d)1783 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1784     const std::chrono::minutes& d) {
1785   return time_internal::FromChrono(d);
1786 }
FromChrono(const std::chrono::hours & d)1787 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1788     const std::chrono::hours& d) {
1789   return time_internal::FromChrono(d);
1790 }
1791 
FromUnixNanos(int64_t ns)1792 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixNanos(int64_t ns) {
1793   return time_internal::FromUnixDuration(Nanoseconds(ns));
1794 }
1795 
FromUnixMicros(int64_t us)1796 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixMicros(int64_t us) {
1797   return time_internal::FromUnixDuration(Microseconds(us));
1798 }
1799 
FromUnixMillis(int64_t ms)1800 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixMillis(int64_t ms) {
1801   return time_internal::FromUnixDuration(Milliseconds(ms));
1802 }
1803 
FromUnixSeconds(int64_t s)1804 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixSeconds(int64_t s) {
1805   return time_internal::FromUnixDuration(Seconds(s));
1806 }
1807 
FromTimeT(time_t t)1808 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromTimeT(time_t t) {
1809   return time_internal::FromUnixDuration(Seconds(t));
1810 }
1811 
1812 ABSL_NAMESPACE_END
1813 }  // namespace absl
1814 
1815 #endif  // ABSL_TIME_TIME_H_
1816