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