Coverage Report

Created: 2026-07-16 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/abseil-cpp/absl/time/time.h
Line
Count
Source
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 =
138
    std::enable_if_t<std::is_integral_v<T> || std::is_enum_v<T>, int>;
139
template <typename T>
140
using EnableIfFloat = std::enable_if_t<std::is_floating_point_v<T>, int>;
141
}  // namespace time_internal
142
143
// Duration
144
//
145
// The `absl::Duration` class represents a signed, fixed-length amount of time.
146
// A `Duration` is generated using a unit-specific factory function, or is
147
// the result of subtracting one `absl::Time` from another. Durations behave
148
// like unit-safe integers and they support all the natural integer-like
149
// arithmetic operations. Arithmetic overflows and saturates at +/- infinity.
150
// `Duration` is trivially destructible and should be passed by value rather
151
// 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.
185
0
  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.
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
0
  Duration& operator*=(T r) {
215
0
    int64_t x = r;
216
0
    return *this *= x;
217
0
  }
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>
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);
247
0
  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
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
0
          lo_(0),
268
0
          hi_(0)
269
#endif
270
0
    {
271
0
      *this = value;
272
0
    }
273
274
0
    constexpr int64_t Get() const {
275
0
      const uint64_t unsigned_value =
276
0
          (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
0
      static_assert(
284
0
          (static_cast<int64_t>((std::numeric_limits<uint64_t>::max)()) ==
285
0
           int64_t{-1}) &&
286
0
              (static_cast<int64_t>(static_cast<uint64_t>(
287
0
                                        (std::numeric_limits<int64_t>::max)()) +
288
0
                                    1) ==
289
0
               (std::numeric_limits<int64_t>::min)()),
290
0
          "static_cast<int64_t>(uint64_t) does not have c++20 semantics");
291
0
      return static_cast<int64_t>(unsigned_value);
292
0
    }
293
294
0
    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
0
      const auto unsigned_value = static_cast<uint64_t>(value);
300
0
      hi_ = static_cast<uint32_t>(unsigned_value >> 32);
301
0
      lo_ = static_cast<uint32_t>(unsigned_value);
302
0
      return *this;
303
0
    }
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
0
                                                       Duration rhs) {
337
0
  return rhs < lhs;
338
0
}
339
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>=(Duration lhs,
340
0
                                                        Duration rhs) {
341
0
  return !(lhs < rhs);
342
0
}
343
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<=(Duration lhs,
344
0
                                                        Duration rhs) {
345
0
  return !(rhs < lhs);
346
0
}
347
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator==(Duration lhs,
348
                                                        Duration rhs);
349
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator!=(Duration lhs,
350
0
                                                        Duration rhs) {
351
0
  return !(lhs == rhs);
352
0
}
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
0
                                                        Duration rhs) {
358
0
  return lhs += rhs;
359
0
}
360
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator-(Duration lhs,
361
0
                                                        Duration rhs) {
362
0
  return lhs -= rhs;
363
0
}
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
0
ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator*(Duration lhs, T rhs) {
413
0
  return lhs *= rhs;
414
0
}
415
template <typename T>
416
0
ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator*(T lhs, Duration rhs) {
417
0
  return rhs *= lhs;
418
0
}
Unexecuted instantiation: absl::Duration absl::operator*<int>(int, absl::Duration)
Unexecuted instantiation: absl::Duration absl::operator*<long>(long, absl::Duration)
Unexecuted instantiation: absl::Duration absl::operator*<double>(double, absl::Duration)
419
template <typename T>
420
0
ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator/(Duration lhs, T rhs) {
421
0
  return lhs /= rhs;
422
0
}
423
ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t operator/(Duration lhs,
424
0
                                                       Duration rhs) {
425
0
  return IDivDuration(lhs, rhs,
426
0
                      &lhs);  // trunc towards zero
427
0
}
428
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator%(Duration lhs,
429
0
                                                        Duration rhs) {
430
0
  return lhs %= rhs;
431
0
}
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.
437
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration ZeroDuration() {
438
0
  return Duration();
439
0
}
440
441
// AbsDuration()
442
//
443
// Returns the absolute value of a duration.
444
0
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration AbsDuration(Duration d) {
445
0
  return (d < ZeroDuration()) ? -d : d;
446
0
}
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>
538
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Nanoseconds(T n) {
539
0
  return time_internal::FromInt64(n, std::nano{});
540
0
}
Unexecuted instantiation: _ZN4absl11NanosecondsIiTnNSt3__19enable_ifIXoosr3stdE13is_integral_vIT_Esr3stdE9is_enum_vIS3_EEiE4typeELi0EEENS_8DurationES3_
Unexecuted instantiation: _ZN4absl11NanosecondsIlTnNSt3__19enable_ifIXoosr3stdE13is_integral_vIT_Esr3stdE9is_enum_vIS3_EEiE4typeELi0EEENS_8DurationES3_
541
template <typename T, time_internal::EnableIfIntegral<T> = 0>
542
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Microseconds(T n) {
543
0
  return time_internal::FromInt64(n, std::micro{});
544
0
}
Unexecuted instantiation: _ZN4absl12MicrosecondsIiTnNSt3__19enable_ifIXoosr3stdE13is_integral_vIT_Esr3stdE9is_enum_vIS3_EEiE4typeELi0EEENS_8DurationES3_
Unexecuted instantiation: _ZN4absl12MicrosecondsIlTnNSt3__19enable_ifIXoosr3stdE13is_integral_vIT_Esr3stdE9is_enum_vIS3_EEiE4typeELi0EEENS_8DurationES3_
545
template <typename T, time_internal::EnableIfIntegral<T> = 0>
546
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Milliseconds(T n) {
547
0
  return time_internal::FromInt64(n, std::milli{});
548
0
}
Unexecuted instantiation: _ZN4absl12MillisecondsIiTnNSt3__19enable_ifIXoosr3stdE13is_integral_vIT_Esr3stdE9is_enum_vIS3_EEiE4typeELi0EEENS_8DurationES3_
Unexecuted instantiation: _ZN4absl12MillisecondsIlTnNSt3__19enable_ifIXoosr3stdE13is_integral_vIT_Esr3stdE9is_enum_vIS3_EEiE4typeELi0EEENS_8DurationES3_
549
template <typename T, time_internal::EnableIfIntegral<T> = 0>
550
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Seconds(T n) {
551
0
  return time_internal::FromInt64(n, std::ratio<1>{});
552
0
}
Unexecuted instantiation: _ZN4absl7SecondsIlTnNSt3__19enable_ifIXoosr3stdE13is_integral_vIT_Esr3stdE9is_enum_vIS3_EEiE4typeELi0EEENS_8DurationES3_
Unexecuted instantiation: _ZN4absl7SecondsIiTnNSt3__19enable_ifIXoosr3stdE13is_integral_vIT_Esr3stdE9is_enum_vIS3_EEiE4typeELi0EEENS_8DurationES3_
553
template <typename T, time_internal::EnableIfIntegral<T> = 0>
554
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Minutes(T n) {
555
0
  return time_internal::FromInt64(n, std::ratio<60>{});
556
0
}
557
template <typename T, time_internal::EnableIfIntegral<T> = 0>
558
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Hours(T n) {
559
0
  return time_internal::FromInt64(n, std::ratio<3600>{});
560
0
}
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>
572
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Nanoseconds(T n) {
573
  return n * Nanoseconds(1);
574
}
575
template <typename T, time_internal::EnableIfFloat<T> = 0>
576
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Microseconds(T n) {
577
  return n * Microseconds(1);
578
}
579
template <typename T, time_internal::EnableIfFloat<T> = 0>
580
0
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Milliseconds(T n) {
581
0
  return n * Milliseconds(1);
582
0
}
583
template <typename T, time_internal::EnableIfFloat<T> = 0>
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)) return -InfiniteDuration();
592
    if (n <= static_cast<T>((std::numeric_limits<int64_t>::min)())) {
593
      return -InfiniteDuration();
594
    }
595
    return -time_internal::MakePosDoubleDuration(-n);
596
  }
597
}
598
template <typename T, time_internal::EnableIfFloat<T> = 0>
599
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Minutes(T n) {
600
  return n * Minutes(1);
601
}
602
template <typename T, time_internal::EnableIfFloat<T> = 0>
603
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Hours(T n) {
604
  return n * Hours(1);
605
}
606
607
// ToInt64Nanoseconds()
608
// ToInt64Microseconds()
609
// ToInt64Milliseconds()
610
// ToInt64Seconds()
611
// ToInt64Minutes()
612
// ToInt64Hours()
613
//
614
// Helper functions that convert a Duration to an integral count of the
615
// indicated unit. These return the same results as the `IDivDuration()`
616
// function, though they usually do so more efficiently; see the
617
// documentation of `IDivDuration()` for details about overflow, etc.
618
//
619
// Example:
620
//
621
//   absl::Duration d = absl::Milliseconds(1500);
622
//   int64_t isec = absl::ToInt64Seconds(d);  // isec == 1
623
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t ToInt64Nanoseconds(Duration d);
624
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t ToInt64Microseconds(Duration d);
625
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t ToInt64Milliseconds(Duration d);
626
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t ToInt64Seconds(Duration d);
627
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t ToInt64Minutes(Duration d);
628
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t ToInt64Hours(Duration d);
629
630
// ToDoubleNanoseconds()
631
// ToDoubleMicroseconds()
632
// ToDoubleMilliseconds()
633
// ToDoubleSeconds()
634
// ToDoubleMinutes()
635
// ToDoubleHours()
636
//
637
// Helper functions that convert a Duration to a floating point count of the
638
// indicated unit. These functions are shorthand for the `FDivDuration()`
639
// function above; see its documentation for details about overflow, etc.
640
//
641
// Example:
642
//
643
//   absl::Duration d = absl::Milliseconds(1500);
644
//   double dsec = absl::ToDoubleSeconds(d);  // dsec == 1.5
645
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleNanoseconds(Duration d);
646
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMicroseconds(Duration d);
647
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMilliseconds(Duration d);
648
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleSeconds(Duration d);
649
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMinutes(Duration d);
650
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleHours(Duration d);
651
652
// FromChrono()
653
//
654
// Converts any of the pre-defined std::chrono durations to an absl::Duration.
655
//
656
// Example:
657
//
658
//   std::chrono::milliseconds ms(123);
659
//   absl::Duration d = absl::FromChrono(ms);
660
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
661
    const std::chrono::nanoseconds& d);
662
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
663
    const std::chrono::microseconds& d);
664
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
665
    const std::chrono::milliseconds& d);
666
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
667
    const std::chrono::seconds& d);
668
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
669
    const std::chrono::minutes& d);
670
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
671
    const std::chrono::hours& d);
672
673
// ToChronoNanoseconds()
674
// ToChronoMicroseconds()
675
// ToChronoMilliseconds()
676
// ToChronoSeconds()
677
// ToChronoMinutes()
678
// ToChronoHours()
679
//
680
// Converts an absl::Duration to any of the pre-defined std::chrono durations.
681
// If overflow would occur, the returned value will saturate at the min/max
682
// chrono duration value instead.
683
//
684
// Example:
685
//
686
//   absl::Duration d = absl::Microseconds(123);
687
//   auto x = absl::ToChronoMicroseconds(d);
688
//   auto y = absl::ToChronoNanoseconds(d);  // x == y
689
//   auto z = absl::ToChronoSeconds(absl::InfiniteDuration());
690
//   // z == std::chrono::seconds::max()
691
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::nanoseconds ToChronoNanoseconds(
692
    Duration d);
693
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::microseconds ToChronoMicroseconds(
694
    Duration d);
695
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::milliseconds ToChronoMilliseconds(
696
    Duration d);
697
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::seconds ToChronoSeconds(Duration d);
698
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::minutes ToChronoMinutes(Duration d);
699
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::hours ToChronoHours(Duration d);
700
701
// FormatDuration()
702
//
703
// Returns a string representing the duration in the form "72h3m0.5s".
704
// Returns "inf" or "-inf" for +/- `InfiniteDuration()`.
705
ABSL_ATTRIBUTE_CONST_FUNCTION std::string FormatDuration(Duration d);
706
707
// Output stream operator.
708
0
inline std::ostream& operator<<(std::ostream& os, Duration d) {
709
0
  return os << FormatDuration(d);
710
0
}
711
712
// Support for StrFormat(), StrCat() etc.
713
template <typename Sink>
714
void AbslStringify(Sink& sink, Duration d) {
715
  sink.Append(FormatDuration(d));
716
}
717
718
// ParseDuration()
719
//
720
// Parses a duration string consisting of a possibly signed sequence of
721
// decimal numbers, each with an optional fractional part and a unit
722
// suffix.  The valid suffixes are "ns", "us" "ms", "s", "m", and "h".
723
// Simple examples include "300ms", "-1.5h", and "2h45m".  Parses "0" as
724
// `ZeroDuration()`. Parses "inf" and "-inf" as +/- `InfiniteDuration()`.
725
bool ParseDuration(absl::string_view dur_string, Duration* d);
726
727
// AbslParseFlag()
728
//
729
// Parses a command-line flag string representation `text` into a Duration
730
// value. Duration flags must be specified in a format that is valid input for
731
// `absl::ParseDuration()`.
732
bool AbslParseFlag(absl::string_view text, Duration* dst, std::string* error);
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` is
752
// trivially destructible and should be passed by value rather than const
753
// reference.
754
//
755
// `absl::Time` assumes there are 60 seconds in a minute, which means the
756
// underlying time scales must be "smeared" to eliminate leap seconds.
757
// See https://developers.google.com/time/smear.
758
//
759
// Even though `absl::Time` supports a wide range of timestamps, exercise
760
// caution when using values in the distant past. `absl::Time` uses the
761
// Proleptic Gregorian calendar, which extends the Gregorian calendar backward
762
// to dates before its introduction in 1582.
763
// See https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar
764
// for more information. Use the ICU calendar classes to convert a date in
765
// some other calendar (http://userguide.icu-project.org/datetime/calendar).
766
//
767
// Similarly, standardized time zones are a reasonably recent innovation, with
768
// the Greenwich prime meridian being established in 1884. The TZ database
769
// itself does not profess accurate offsets for timestamps prior to 1970. The
770
// breakdown of future timestamps is subject to the whim of regional
771
// governments.
772
//
773
// The `absl::Time` class represents an instant in time as a count of clock
774
// ticks of some granularity (resolution) from some starting point (epoch).
775
//
776
// `absl::Time` uses a resolution that is high enough to avoid loss in
777
// precision, and a range that is wide enough to avoid overflow, when
778
// converting between tick counts in most Google time scales (i.e., resolution
779
// of at least one nanosecond, and range +/-100 billion years).  Conversions
780
// between the time scales are performed by truncating (towards negative
781
// infinity) to the nearest representable point.
782
//
783
// Examples:
784
//
785
//   absl::Time t1 = ...;
786
//   absl::Time t2 = t1 + absl::Minutes(2);
787
//   absl::Duration d = t2 - t1;  // == absl::Minutes(2)
788
//
789
class Time {
790
 public:
791
  // Value semantics.
792
793
  // Returns the Unix epoch.  However, those reading your code may not know
794
  // or expect the Unix epoch as the default value, so make your code more
795
  // readable by explicitly initializing all instances before use.
796
  //
797
  // Example:
798
  //   absl::Time t = absl::UnixEpoch();
799
  //   absl::Time t = absl::Now();
800
  //   absl::Time t = absl::TimeFromTimeval(tv);
801
  //   absl::Time t = absl::InfinitePast();
802
0
  constexpr Time() = default;
803
804
  // Copyable.
805
  constexpr Time(const Time& t) = default;
806
  Time& operator=(const Time& t) = default;
807
808
  // Assignment operators.
809
0
  Time& operator+=(Duration d) {
810
0
    rep_ += d;
811
0
    return *this;
812
0
  }
813
0
  Time& operator-=(Duration d) {
814
0
    rep_ -= d;
815
0
    return *this;
816
0
  }
817
818
  // Time::Breakdown
819
  //
820
  // The calendar and wall-clock (aka "civil time") components of an
821
  // `absl::Time` in a certain `absl::TimeZone`. This struct is not
822
  // intended to represent an instant in time. So, rather than passing
823
  // a `Time::Breakdown` to a function, pass an `absl::Time` and an
824
  // `absl::TimeZone`.
825
  //
826
  // Deprecated. Use `absl::TimeZone::CivilInfo`.
827
  struct ABSL_DEPRECATED("Use `absl::TimeZone::CivilInfo`.") Breakdown {
828
    int64_t year;        // year (e.g., 2013)
829
    int month;           // month of year [1:12]
830
    int day;             // day of month [1:31]
831
    int hour;            // hour of day [0:23]
832
    int minute;          // minute of hour [0:59]
833
    int second;          // second of minute [0:59]
834
    Duration subsecond;  // [Seconds(0):Seconds(1)) if finite
835
    int weekday;         // 1==Mon, ..., 7=Sun
836
    int yearday;         // day of year [1:366]
837
838
    // Note: The following fields exist for backward compatibility
839
    // with older APIs.  Accessing these fields directly is a sign of
840
    // imprudent logic in the calling code.  Modern time-related code
841
    // should only access this data indirectly by way of FormatTime().
842
    // These fields are undefined for InfiniteFuture() and InfinitePast().
843
    int offset;             // seconds east of UTC
844
    bool is_dst;            // is offset non-standard?
845
    const char* zone_abbr;  // time-zone abbreviation (e.g., "PST")
846
  };
847
848
  // Time::In()
849
  //
850
  // Returns the breakdown of this instant in the given TimeZone.
851
  //
852
  // Deprecated. Use `absl::TimeZone::At(Time)`.
853
  ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING
854
  ABSL_DEPRECATED("Use `absl::TimeZone::At(Time)`.")
855
  Breakdown In(TimeZone tz) const;
856
  ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING
857
858
  template <typename H>
859
  friend H AbslHashValue(H h, Time t) {
860
    return H::combine(std::move(h), t.rep_);
861
  }
862
863
 private:
864
  friend constexpr Time time_internal::FromUnixDuration(Duration d);
865
  friend constexpr Duration time_internal::ToUnixDuration(Time t);
866
867
#ifdef ABSL_INTERNAL_TIME_HAS_THREE_WAY_COMPARISON
868
  friend constexpr std::strong_ordering operator<=>(Time lhs, Time rhs);
869
#endif  // ABSL_INTERNAL_TIME_HAS_THREE_WAY_COMPARISON
870
871
  friend constexpr bool operator<(Time lhs, Time rhs);
872
  friend constexpr bool operator==(Time lhs, Time rhs);
873
  friend Duration operator-(Time lhs, Time rhs);
874
  friend constexpr Time UniversalEpoch();
875
  friend constexpr Time InfiniteFuture();
876
  friend constexpr Time InfinitePast();
877
0
  constexpr explicit Time(Duration rep) : rep_(rep) {}
878
  Duration rep_;
879
};
880
881
// Relational Operators
882
#ifdef ABSL_INTERNAL_TIME_HAS_THREE_WAY_COMPARISON
883
884
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr std::strong_ordering operator<=>(
885
    Time lhs, Time rhs) {
886
  return lhs.rep_ <=> rhs.rep_;
887
}
888
889
#endif  // ABSL_INTERNAL_TIME_HAS_THREE_WAY_COMPARISON
890
891
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<(Time lhs, Time rhs) {
892
0
  return lhs.rep_ < rhs.rep_;
893
0
}
894
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>(Time lhs, Time rhs) {
895
0
  return rhs < lhs;
896
0
}
897
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>=(Time lhs, Time rhs) {
898
0
  return !(lhs < rhs);
899
0
}
900
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<=(Time lhs, Time rhs) {
901
0
  return !(rhs < lhs);
902
0
}
903
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator==(Time lhs, Time rhs) {
904
0
  return lhs.rep_ == rhs.rep_;
905
0
}
906
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator!=(Time lhs, Time rhs) {
907
0
  return !(lhs == rhs);
908
0
}
909
910
// Additive Operators
911
0
ABSL_ATTRIBUTE_CONST_FUNCTION inline Time operator+(Time lhs, Duration rhs) {
912
0
  return lhs += rhs;
913
0
}
914
0
ABSL_ATTRIBUTE_CONST_FUNCTION inline Time operator+(Duration lhs, Time rhs) {
915
0
  return rhs += lhs;
916
0
}
917
0
ABSL_ATTRIBUTE_CONST_FUNCTION inline Time operator-(Time lhs, Duration rhs) {
918
0
  return lhs -= rhs;
919
0
}
920
0
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator-(Time lhs, Time rhs) {
921
0
  return lhs.rep_ - rhs.rep_;
922
0
}
923
924
// UnixEpoch()
925
//
926
// Returns the `absl::Time` representing "1970-01-01 00:00:00.0 +0000".
927
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time UnixEpoch() { return Time(); }
928
929
// UniversalEpoch()
930
//
931
// Returns the `absl::Time` representing "0001-01-01 00:00:00.0 +0000", the
932
// epoch of the ICU Universal Time Scale.
933
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time UniversalEpoch() {
934
  // 719162 is the number of days from 0001-01-01 to 1970-01-01,
935
  // assuming the Gregorian calendar.
936
0
  return Time(
937
0
      time_internal::MakeDuration(-24 * 719162 * int64_t{3600}, uint32_t{0}));
938
0
}
939
940
// InfiniteFuture()
941
//
942
// Returns an `absl::Time` that is infinitely far in the future.
943
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time InfiniteFuture() {
944
0
  return Time(time_internal::MakeDuration((std::numeric_limits<int64_t>::max)(),
945
0
                                          ~uint32_t{0}));
946
0
}
947
948
// InfinitePast()
949
//
950
// Returns an `absl::Time` that is infinitely far in the past.
951
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time InfinitePast() {
952
0
  return Time(time_internal::MakeDuration((std::numeric_limits<int64_t>::min)(),
953
0
                                          ~uint32_t{0}));
954
0
}
955
956
// FromUnixNanos()
957
// FromUnixMicros()
958
// FromUnixMillis()
959
// FromUnixSeconds()
960
// FromTimeT()
961
// FromUDate()
962
// FromUniversal()
963
//
964
// Creates an `absl::Time` from a variety of other representations.  See
965
// https://unicode-org.github.io/icu/userguide/datetime/universaltimescale.html
966
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixNanos(int64_t ns);
967
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixMicros(int64_t us);
968
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixMillis(int64_t ms);
969
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixSeconds(int64_t s);
970
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromTimeT(time_t t);
971
ABSL_ATTRIBUTE_CONST_FUNCTION Time FromUDate(double udate);
972
ABSL_ATTRIBUTE_CONST_FUNCTION Time FromUniversal(int64_t universal);
973
974
// ToUnixNanos()
975
// ToUnixMicros()
976
// ToUnixMillis()
977
// ToUnixSeconds()
978
// ToTimeT()
979
// ToUDate()
980
// ToUniversal()
981
//
982
// Converts an `absl::Time` to a variety of other representations.  See
983
// https://unicode-org.github.io/icu/userguide/datetime/universaltimescale.html
984
//
985
// Note that these operations round down toward negative infinity where
986
// necessary to adjust to the resolution of the result type.  Beware of
987
// possible time_t over/underflow in ToTime{T,val,spec}() on 32-bit platforms.
988
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixNanos(Time t);
989
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixMicros(Time t);
990
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixMillis(Time t);
991
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixSeconds(Time t);
992
ABSL_ATTRIBUTE_CONST_FUNCTION time_t ToTimeT(Time t);
993
ABSL_ATTRIBUTE_CONST_FUNCTION double ToUDate(Time t);
994
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUniversal(Time t);
995
996
// DurationFromTimespec()
997
// DurationFromTimeval()
998
// ToTimespec()
999
// ToTimeval()
1000
// TimeFromTimespec()
1001
// TimeFromTimeval()
1002
// ToTimespec()
1003
// ToTimeval()
1004
//
1005
// Some APIs use a timespec or a timeval as a Duration (e.g., nanosleep(2)
1006
// and select(2)), while others use them as a Time (e.g. clock_gettime(2)
1007
// and gettimeofday(2)), so conversion functions are provided for both cases.
1008
// The "to timespec/val" direction is easily handled via overloading, but
1009
// for "from timespec/val" the desired type is part of the function name.
1010
ABSL_ATTRIBUTE_CONST_FUNCTION Duration DurationFromTimespec(timespec ts);
1011
ABSL_ATTRIBUTE_CONST_FUNCTION Duration DurationFromTimeval(timeval tv);
1012
ABSL_ATTRIBUTE_CONST_FUNCTION timespec ToTimespec(Duration d);
1013
ABSL_ATTRIBUTE_CONST_FUNCTION timeval ToTimeval(Duration d);
1014
ABSL_ATTRIBUTE_CONST_FUNCTION Time TimeFromTimespec(timespec ts);
1015
ABSL_ATTRIBUTE_CONST_FUNCTION Time TimeFromTimeval(timeval tv);
1016
ABSL_ATTRIBUTE_CONST_FUNCTION timespec ToTimespec(Time t);
1017
ABSL_ATTRIBUTE_CONST_FUNCTION timeval ToTimeval(Time t);
1018
1019
// FromChrono()
1020
//
1021
// Converts a std::chrono::system_clock::time_point to an absl::Time.
1022
//
1023
// Example:
1024
//
1025
//   auto tp = std::chrono::system_clock::from_time_t(123);
1026
//   absl::Time t = absl::FromChrono(tp);
1027
//   // t == absl::FromTimeT(123)
1028
ABSL_ATTRIBUTE_PURE_FUNCTION Time
1029
FromChrono(const std::chrono::system_clock::time_point& tp);
1030
1031
// ToChronoTime()
1032
//
1033
// Converts an absl::Time to a std::chrono::system_clock::time_point. If
1034
// overflow would occur, the returned value will saturate at the min/max time
1035
// point value instead.
1036
//
1037
// Example:
1038
//
1039
//   absl::Time t = absl::FromTimeT(123);
1040
//   auto tp = absl::ToChronoTime(t);
1041
//   // tp == std::chrono::system_clock::from_time_t(123);
1042
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::system_clock::time_point
1043
    ToChronoTime(Time);
1044
1045
// AbslParseFlag()
1046
//
1047
// Parses the command-line flag string representation `text` into a Time value.
1048
// Time flags must be specified in a format that matches absl::RFC3339_full.
1049
//
1050
// For example:
1051
//
1052
//   --start_time=2016-01-02T03:04:05.678+08:00
1053
//
1054
// Note: A UTC offset (or 'Z' indicating a zero-offset from UTC) is required.
1055
//
1056
// Additionally, if you'd like to specify a time as a count of
1057
// seconds/milliseconds/etc from the Unix epoch, use an absl::Duration flag
1058
// and add that duration to absl::UnixEpoch() to get an absl::Time.
1059
bool AbslParseFlag(absl::string_view text, Time* t, std::string* error);
1060
1061
// AbslUnparseFlag()
1062
//
1063
// Unparses a Time value into a command-line string representation using
1064
// the format specified by `absl::ParseTime()`.
1065
std::string AbslUnparseFlag(Time t);
1066
1067
// TimeZone
1068
//
1069
// The `absl::TimeZone` is an opaque, small, value-type class representing a
1070
// geo-political region within which particular rules are used for converting
1071
// between absolute and civil times (see https://git.io/v59Ly). `absl::TimeZone`
1072
// values are named using the TZ identifiers from the IANA Time Zone Database,
1073
// such as "America/Los_Angeles" or "Australia/Sydney". `absl::TimeZone` values
1074
// are created from factory functions such as `absl::LoadTimeZone()`. Note:
1075
// strings like "PST" and "EDT" are not valid TZ identifiers. Prefer to pass by
1076
// value rather than const reference.
1077
//
1078
// For more on the fundamental concepts of time zones, absolute times, and civil
1079
// times, see https://github.com/google/cctz#fundamental-concepts
1080
//
1081
// Examples:
1082
//
1083
//   absl::TimeZone utc = absl::UTCTimeZone();
1084
//   absl::TimeZone pst = absl::FixedTimeZone(-8 * 60 * 60);
1085
//   absl::TimeZone loc = absl::LocalTimeZone();
1086
//   absl::TimeZone lax;
1087
//   if (!absl::LoadTimeZone("America/Los_Angeles", &lax)) {
1088
//     // handle error case
1089
//   }
1090
//
1091
// See also:
1092
// - https://github.com/google/cctz
1093
// - https://www.iana.org/time-zones
1094
// - https://en.wikipedia.org/wiki/Zoneinfo
1095
class TimeZone {
1096
 public:
1097
0
  explicit TimeZone(time_internal::cctz::time_zone tz) : cz_(tz) {}
1098
  TimeZone() = default;  // UTC, but prefer UTCTimeZone() to be explicit.
1099
1100
  // Copyable.
1101
  TimeZone(const TimeZone&) = default;
1102
  TimeZone& operator=(const TimeZone&) = default;
1103
1104
0
  explicit operator time_internal::cctz::time_zone() const { return cz_; }
1105
1106
0
  std::string name() const { return cz_.name(); }
1107
1108
  // TimeZone::CivilInfo
1109
  //
1110
  // Information about the civil time corresponding to an absolute time.
1111
  // This struct is not intended to represent an instant in time. So, rather
1112
  // than passing a `TimeZone::CivilInfo` to a function, pass an `absl::Time`
1113
  // and an `absl::TimeZone`.
1114
  struct CivilInfo {
1115
    CivilSecond cs;
1116
    Duration subsecond;
1117
1118
    // Note: The following fields exist for backward compatibility
1119
    // with older APIs.  Accessing these fields directly is a sign of
1120
    // imprudent logic in the calling code.  Modern time-related code
1121
    // should only access this data indirectly by way of FormatTime().
1122
    // These fields are undefined for InfiniteFuture() and InfinitePast().
1123
    int offset;             // seconds east of UTC
1124
    bool is_dst;            // is offset non-standard?
1125
    const char* zone_abbr;  // time-zone abbreviation (e.g., "PST")
1126
  };
1127
1128
  // TimeZone::At(Time)
1129
  //
1130
  // Returns the civil time for this TimeZone at a certain `absl::Time`.
1131
  // If the input time is infinite, the output civil second will be set to
1132
  // CivilSecond::max() or min(), and the subsecond will be infinite.
1133
  //
1134
  // Example:
1135
  //
1136
  //   const auto epoch = lax.At(absl::UnixEpoch());
1137
  //   // epoch.cs == 1969-12-31 16:00:00
1138
  //   // epoch.subsecond == absl::ZeroDuration()
1139
  //   // epoch.offset == -28800
1140
  //   // epoch.is_dst == false
1141
  //   // epoch.abbr == "PST"
1142
  CivilInfo At(Time t) const;
1143
1144
  // TimeZone::TimeInfo
1145
  //
1146
  // Information about the absolute times corresponding to a civil time.
1147
  // (Subseconds must be handled separately.)
1148
  //
1149
  // It is possible for a caller to pass a civil-time value that does
1150
  // not represent an actual or unique instant in time (due to a shift
1151
  // in UTC offset in the TimeZone, which results in a discontinuity in
1152
  // the civil-time components). For example, a daylight-saving-time
1153
  // transition skips or repeats civil times---in the United States,
1154
  // March 13, 2011 02:15 never occurred, while November 6, 2011 01:15
1155
  // occurred twice---so requests for such times are not well-defined.
1156
  // To account for these possibilities, `absl::TimeZone::TimeInfo` is
1157
  // richer than just a single `absl::Time`.
1158
  struct TimeInfo {
1159
    enum CivilKind {
1160
      UNIQUE,    // the civil time was singular (pre == trans == post)
1161
      SKIPPED,   // the civil time did not exist (pre >= trans > post)
1162
      REPEATED,  // the civil time was ambiguous (pre < trans <= post)
1163
    } kind;
1164
    Time pre;    // time calculated using the pre-transition offset
1165
    Time trans;  // when the civil-time discontinuity occurred
1166
    Time post;   // time calculated using the post-transition offset
1167
  };
1168
1169
  // TimeZone::At(CivilSecond)
1170
  //
1171
  // Returns an `absl::TimeInfo` containing the absolute time(s) for this
1172
  // TimeZone at an `absl::CivilSecond`. When the civil time is skipped or
1173
  // repeated, returns times calculated using the pre-transition and post-
1174
  // transition UTC offsets, plus the transition time itself.
1175
  //
1176
  // Examples:
1177
  //
1178
  //   // A unique civil time
1179
  //   const auto jan01 = lax.At(absl::CivilSecond(2011, 1, 1, 0, 0, 0));
1180
  //   // jan01.kind == TimeZone::TimeInfo::UNIQUE
1181
  //   // jan01.pre    is 2011-01-01 00:00:00 -0800
1182
  //   // jan01.trans  is 2011-01-01 00:00:00 -0800
1183
  //   // jan01.post   is 2011-01-01 00:00:00 -0800
1184
  //
1185
  //   // A Spring DST transition, when there is a gap in civil time
1186
  //   const auto mar13 = lax.At(absl::CivilSecond(2011, 3, 13, 2, 15, 0));
1187
  //   // mar13.kind == TimeZone::TimeInfo::SKIPPED
1188
  //   // mar13.pre   is 2011-03-13 03:15:00 -0700
1189
  //   // mar13.trans is 2011-03-13 03:00:00 -0700
1190
  //   // mar13.post  is 2011-03-13 01:15:00 -0800
1191
  //
1192
  //   // A Fall DST transition, when civil times are repeated
1193
  //   const auto nov06 = lax.At(absl::CivilSecond(2011, 11, 6, 1, 15, 0));
1194
  //   // nov06.kind == TimeZone::TimeInfo::REPEATED
1195
  //   // nov06.pre   is 2011-11-06 01:15:00 -0700
1196
  //   // nov06.trans is 2011-11-06 01:00:00 -0800
1197
  //   // nov06.post  is 2011-11-06 01:15:00 -0800
1198
  TimeInfo At(CivilSecond ct) const;
1199
1200
  // TimeZone::NextTransition()
1201
  // TimeZone::PrevTransition()
1202
  //
1203
  // Finds the time of the next/previous offset change in this time zone.
1204
  //
1205
  // By definition, `NextTransition(t, &trans)` returns false when `t` is
1206
  // `InfiniteFuture()`, and `PrevTransition(t, &trans)` returns false
1207
  // when `t` is `InfinitePast()`. If the zone has no transitions, the
1208
  // result will also be false no matter what the argument.
1209
  //
1210
  // Otherwise, when `t` is `InfinitePast()`, `NextTransition(t, &trans)`
1211
  // returns true and sets `trans` to the first recorded transition. Chains
1212
  // of calls to `NextTransition()/PrevTransition()` will eventually return
1213
  // false, but it is unspecified exactly when `NextTransition(t, &trans)`
1214
  // jumps to false, or what time is set by `PrevTransition(t, &trans)` for
1215
  // a very distant `t`.
1216
  //
1217
  // Note: Enumeration of time-zone transitions is for informational purposes
1218
  // only. Modern time-related code should not care about when offset changes
1219
  // occur.
1220
  //
1221
  // Example:
1222
  //   absl::TimeZone nyc;
1223
  //   if (!absl::LoadTimeZone("America/New_York", &nyc)) { ... }
1224
  //   const auto now = absl::Now();
1225
  //   auto t = absl::InfinitePast();
1226
  //   absl::TimeZone::CivilTransition trans;
1227
  //   while (t <= now && nyc.NextTransition(t, &trans)) {
1228
  //     // transition: trans.from -> trans.to
1229
  //     t = nyc.At(trans.to).trans;
1230
  //   }
1231
  struct CivilTransition {
1232
    CivilSecond from;  // the civil time we jump from
1233
    CivilSecond to;    // the civil time we jump to
1234
  };
1235
  bool NextTransition(Time t, CivilTransition* trans) const;
1236
  bool PrevTransition(Time t, CivilTransition* trans) const;
1237
1238
  template <typename H>
1239
  friend H AbslHashValue(H h, TimeZone tz) {
1240
    return H::combine(std::move(h), tz.cz_);
1241
  }
1242
1243
 private:
1244
0
  friend bool operator==(TimeZone a, TimeZone b) { return a.cz_ == b.cz_; }
1245
0
  friend bool operator!=(TimeZone a, TimeZone b) { return a.cz_ != b.cz_; }
1246
0
  friend std::ostream& operator<<(std::ostream& os, TimeZone tz) {
1247
0
    return os << tz.name();
1248
0
  }
1249
1250
  time_internal::cctz::time_zone cz_;
1251
};
1252
1253
// LoadTimeZone()
1254
//
1255
// Loads the named zone. May perform I/O on the initial load of the named
1256
// zone. If the name is invalid, or some other kind of error occurs, returns
1257
// `false` and `*tz` is set to the UTC time zone.
1258
0
inline bool LoadTimeZone(absl::string_view name, TimeZone* tz) {
1259
0
  if (name == "localtime") {
1260
0
    *tz = TimeZone(time_internal::cctz::local_time_zone());
1261
0
    return true;
1262
0
  }
1263
0
  time_internal::cctz::time_zone cz;
1264
0
  const bool b = time_internal::cctz::load_time_zone(std::string(name), &cz);
1265
0
  *tz = TimeZone(cz);
1266
0
  return b;
1267
0
}
1268
1269
// FixedTimeZone()
1270
//
1271
// Returns a TimeZone that is a fixed offset (seconds east) from UTC.
1272
// Note: If the absolute value of the offset is greater than 24 hours
1273
// you'll get UTC (i.e., no offset) instead.
1274
0
inline TimeZone FixedTimeZone(int seconds) {
1275
0
  return TimeZone(
1276
0
      time_internal::cctz::fixed_time_zone(std::chrono::seconds(seconds)));
1277
0
}
1278
1279
// UTCTimeZone()
1280
//
1281
// Convenience method returning the UTC time zone.
1282
0
inline TimeZone UTCTimeZone() {
1283
0
  return TimeZone(time_internal::cctz::utc_time_zone());
1284
0
}
1285
1286
// LocalTimeZone()
1287
//
1288
// Convenience method returning the local time zone, or UTC if there is
1289
// no configured local zone.  Warning: Be wary of using LocalTimeZone(),
1290
// and particularly so in a server process, as the zone configured for the
1291
// local machine should be irrelevant.  Prefer an explicit zone name.
1292
0
inline TimeZone LocalTimeZone() {
1293
0
  return TimeZone(time_internal::cctz::local_time_zone());
1294
0
}
1295
1296
// ToCivilSecond()
1297
// ToCivilMinute()
1298
// ToCivilHour()
1299
// ToCivilDay()
1300
// ToCivilMonth()
1301
// ToCivilYear()
1302
//
1303
// Helpers for TimeZone::At(Time) to return particularly aligned civil times.
1304
//
1305
// Example:
1306
//
1307
//   absl::Time t = ...;
1308
//   absl::TimeZone tz = ...;
1309
//   const auto cd = absl::ToCivilDay(t, tz);
1310
ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilSecond ToCivilSecond(Time t,
1311
0
                                                              TimeZone tz) {
1312
0
  return tz.At(t).cs;  // already a CivilSecond
1313
0
}
1314
ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilMinute ToCivilMinute(Time t,
1315
0
                                                              TimeZone tz) {
1316
0
  return CivilMinute(tz.At(t).cs);
1317
0
}
1318
0
ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilHour ToCivilHour(Time t, TimeZone tz) {
1319
0
  return CivilHour(tz.At(t).cs);
1320
0
}
1321
0
ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilDay ToCivilDay(Time t, TimeZone tz) {
1322
0
  return CivilDay(tz.At(t).cs);
1323
0
}
1324
ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilMonth ToCivilMonth(Time t,
1325
0
                                                            TimeZone tz) {
1326
0
  return CivilMonth(tz.At(t).cs);
1327
0
}
1328
0
ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilYear ToCivilYear(Time t, TimeZone tz) {
1329
0
  return CivilYear(tz.At(t).cs);
1330
0
}
1331
1332
// FromCivil()
1333
//
1334
// Helper for TimeZone::At(CivilSecond) that provides "order-preserving
1335
// semantics." If the civil time maps to a unique time, that time is
1336
// returned. If the civil time is repeated in the given time zone, the
1337
// time using the pre-transition offset is returned. Otherwise, the
1338
// civil time is skipped in the given time zone, and the transition time
1339
// is returned. This means that for any two civil times, ct1 and ct2,
1340
// (ct1 < ct2) => (FromCivil(ct1) <= FromCivil(ct2)), the equal case
1341
// being when two non-existent civil times map to the same transition time.
1342
//
1343
// Note: Accepts civil times of any alignment.
1344
ABSL_ATTRIBUTE_PURE_FUNCTION inline Time FromCivil(CivilSecond ct,
1345
0
                                                   TimeZone tz) {
1346
0
  const auto ti = tz.At(ct);
1347
0
  if (ti.kind == TimeZone::TimeInfo::SKIPPED) return ti.trans;
1348
0
  return ti.pre;
1349
0
}
1350
1351
// TimeConversion
1352
//
1353
// An `absl::TimeConversion` represents the conversion of year, month, day,
1354
// hour, minute, and second values (i.e., a civil time), in a particular
1355
// `absl::TimeZone`, to a time instant (an absolute time), as returned by
1356
// `absl::ConvertDateTime()`. Legacy version of `absl::TimeZone::TimeInfo`.
1357
//
1358
// Deprecated. Use `absl::TimeZone::TimeInfo`.
1359
struct ABSL_DEPRECATED("Use `absl::TimeZone::TimeInfo`.") TimeConversion {
1360
  Time pre;    // time calculated using the pre-transition offset
1361
  Time trans;  // when the civil-time discontinuity occurred
1362
  Time post;   // time calculated using the post-transition offset
1363
1364
  enum Kind {
1365
    UNIQUE,    // the civil time was singular (pre == trans == post)
1366
    SKIPPED,   // the civil time did not exist
1367
    REPEATED,  // the civil time was ambiguous
1368
  };
1369
  Kind kind;
1370
1371
  bool normalized;  // input values were outside their valid ranges
1372
};
1373
1374
// ConvertDateTime()
1375
//
1376
// Legacy version of `absl::TimeZone::At(absl::CivilSecond)` that takes
1377
// the civil time as six, separate values (YMDHMS).
1378
//
1379
// The input month, day, hour, minute, and second values can be outside
1380
// of their valid ranges, in which case they will be "normalized" during
1381
// the conversion.
1382
//
1383
// Example:
1384
//
1385
//   // "October 32" normalizes to "November 1".
1386
//   absl::TimeConversion tc =
1387
//       absl::ConvertDateTime(2013, 10, 32, 8, 30, 0, lax);
1388
//   // tc.kind == TimeConversion::UNIQUE && tc.normalized == true
1389
//   // absl::ToCivilDay(tc.pre, tz).month() == 11
1390
//   // absl::ToCivilDay(tc.pre, tz).day() == 1
1391
//
1392
// Deprecated. Use `absl::TimeZone::At(CivilSecond)`.
1393
ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING
1394
ABSL_DEPRECATED("Use `absl::TimeZone::At(CivilSecond)`.")
1395
TimeConversion ConvertDateTime(int64_t year, int mon, int day, int hour,
1396
                               int min, int sec, TimeZone tz);
1397
ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING
1398
1399
// FromDateTime()
1400
//
1401
// A convenience wrapper for `absl::ConvertDateTime()` that simply returns
1402
// the "pre" `absl::Time`.  That is, the unique result, or the instant that
1403
// is correct using the pre-transition offset (as if the transition never
1404
// happened).
1405
//
1406
// Example:
1407
//
1408
//   absl::Time t = absl::FromDateTime(2017, 9, 26, 9, 30, 0, lax);
1409
//   // t = 2017-09-26 09:30:00 -0700
1410
//
1411
// Deprecated. Use `absl::FromCivil(CivilSecond, TimeZone)`. Note that the
1412
// behavior of `FromCivil()` differs from `FromDateTime()` for skipped civil
1413
// times. If you care about that see `absl::TimeZone::At(absl::CivilSecond)`.
1414
ABSL_DEPRECATED("Use `absl::FromCivil(CivilSecond, TimeZone)`.")
1415
inline Time FromDateTime(int64_t year, int mon, int day, int hour, int min,
1416
0
                         int sec, TimeZone tz) {
1417
0
  ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING
1418
0
  return ConvertDateTime(year, mon, day, hour, min, sec, tz).pre;
1419
0
  ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING
1420
0
}
1421
1422
// FromTM()
1423
//
1424
// Converts the `tm_year`, `tm_mon`, `tm_mday`, `tm_hour`, `tm_min`, and
1425
// `tm_sec` fields to an `absl::Time` using the given time zone. See ctime(3)
1426
// for a description of the expected values of the tm fields. If the civil time
1427
// is unique (see `absl::TimeZone::At(absl::CivilSecond)` above), the matching
1428
// time instant is returned.  Otherwise, the `tm_isdst` field is consulted to
1429
// choose between the possible results.  For a repeated civil time, `tm_isdst !=
1430
// 0` returns the matching DST instant, while `tm_isdst == 0` returns the
1431
// matching non-DST instant.  For a skipped civil time there is no matching
1432
// instant, so `tm_isdst != 0` returns the DST instant, and `tm_isdst == 0`
1433
// returns the non-DST instant, that would have matched if the transition never
1434
// happened.
1435
ABSL_ATTRIBUTE_PURE_FUNCTION Time FromTM(const struct tm& tm, TimeZone tz);
1436
1437
// ToTM()
1438
//
1439
// Converts the given `absl::Time` to a struct tm using the given time zone.
1440
// See ctime(3) for a description of the values of the tm fields.
1441
ABSL_ATTRIBUTE_PURE_FUNCTION struct tm ToTM(Time t, TimeZone tz);
1442
1443
// RFC3339_full
1444
// RFC3339_sec
1445
//
1446
// FormatTime()/ParseTime() format specifiers for RFC3339 date/time strings,
1447
// with trailing zeros trimmed or with fractional seconds omitted altogether.
1448
//
1449
// Note that RFC3339_sec[] matches an ISO 8601 extended format for date and
1450
// time with UTC offset.  Also note the use of "%Y": RFC3339 mandates that
1451
// years have exactly four digits, but we allow them to take their natural
1452
// width.
1453
ABSL_DLL extern const char RFC3339_full[];  // %Y-%m-%d%ET%H:%M:%E*S%Ez
1454
ABSL_DLL extern const char RFC3339_sec[];   // %Y-%m-%d%ET%H:%M:%S%Ez
1455
1456
// RFC1123_full
1457
// RFC1123_no_wday
1458
//
1459
// FormatTime()/ParseTime() format specifiers for RFC1123 date/time strings.
1460
ABSL_DLL extern const char RFC1123_full[];     // %a, %d %b %E4Y %H:%M:%S %z
1461
ABSL_DLL extern const char RFC1123_no_wday[];  // %d %b %E4Y %H:%M:%S %z
1462
1463
// FormatTime()
1464
//
1465
// Formats the given `absl::Time` in the `absl::TimeZone` according to the
1466
// provided format string. Uses strftime()-like formatting options, with
1467
// the following extensions:
1468
//
1469
//   - %Ez  - RFC3339-compatible numeric UTC offset (+hh:mm or -hh:mm)
1470
//   - %E*z - Full-resolution numeric UTC offset (+hh:mm:ss or -hh:mm:ss)
1471
//   - %E#S - Seconds with # digits of fractional precision
1472
//   - %E*S - Seconds with full fractional precision (a literal '*')
1473
//   - %E#f - Fractional seconds with # digits of precision
1474
//   - %E*f - Fractional seconds with full precision (a literal '*')
1475
//   - %E4Y - Four-character years (-999 ... -001, 0000, 0001 ... 9999)
1476
//   - %ET  - The RFC3339 "date-time" separator "T"
1477
//
1478
// Note that %E0S behaves like %S, and %E0f produces no characters.  In
1479
// contrast %E*f always produces at least one digit, which may be '0'.
1480
//
1481
// Note that %Y produces as many characters as it takes to fully render the
1482
// year.  A year outside of [-999:9999] when formatted with %E4Y will produce
1483
// more than four characters, just like %Y.
1484
//
1485
// We recommend that format strings include the UTC offset (%z, %Ez, or %E*z)
1486
// so that the result uniquely identifies a time instant.
1487
//
1488
// Example:
1489
//
1490
//   absl::CivilSecond cs(2013, 1, 2, 3, 4, 5);
1491
//   absl::Time t = absl::FromCivil(cs, lax);
1492
//   std::string f = absl::FormatTime("%H:%M:%S", t, lax);  // "03:04:05"
1493
//   f = absl::FormatTime("%H:%M:%E3S", t, lax);  // "03:04:05.000"
1494
//
1495
// Note: If the given `absl::Time` is `absl::InfiniteFuture()`, the returned
1496
// string will be exactly "infinite-future". If the given `absl::Time` is
1497
// `absl::InfinitePast()`, the returned string will be exactly "infinite-past".
1498
// In both cases the given format string and `absl::TimeZone` are ignored.
1499
//
1500
ABSL_ATTRIBUTE_PURE_FUNCTION std::string FormatTime(absl::string_view format,
1501
                                                    Time t, TimeZone tz);
1502
1503
// Convenience functions that format the given time using the RFC3339_full
1504
// format.  The first overload uses the provided TimeZone, while the second
1505
// uses LocalTimeZone().
1506
ABSL_ATTRIBUTE_PURE_FUNCTION std::string FormatTime(Time t, TimeZone tz);
1507
ABSL_ATTRIBUTE_PURE_FUNCTION std::string FormatTime(Time t);
1508
1509
// Output stream operator.
1510
0
inline std::ostream& operator<<(std::ostream& os, Time t) {
1511
0
  return os << FormatTime(t);
1512
0
}
1513
1514
// Support for StrFormat(), StrCat() etc.
1515
template <typename Sink>
1516
void AbslStringify(Sink& sink, Time t) {
1517
  sink.Append(FormatTime(t));
1518
}
1519
1520
// ParseTime()
1521
//
1522
// Parses an input string according to the provided format string and
1523
// returns the corresponding `absl::Time`. Uses strftime()-like formatting
1524
// options, with the same extensions as FormatTime(), but with the
1525
// exceptions that %E#S is interpreted as %E*S, and %E#f as %E*f.  %Ez
1526
// and %E*z also accept the same inputs, which (along with %z) includes
1527
// 'z' and 'Z' as synonyms for +00:00.  %ET accepts either 'T' or 't'.
1528
//
1529
// %Y consumes as many numeric characters as it can, so the matching data
1530
// should always be terminated with a non-numeric.  %E4Y always consumes
1531
// exactly four characters, including any sign.
1532
//
1533
// Unspecified fields are taken from the default date and time of ...
1534
//
1535
//   "1970-01-01 00:00:00.0 +0000"
1536
//
1537
// For example, parsing a string of "15:45" (%H:%M) will return an absl::Time
1538
// that represents "1970-01-01 15:45:00.0 +0000".
1539
//
1540
// Note that since ParseTime() returns time instants, it makes the most sense
1541
// to parse fully-specified date/time strings that include a UTC offset (%z,
1542
// %Ez, or %E*z).
1543
//
1544
// Note also that `absl::ParseTime()` only heeds the fields year, month, day,
1545
// hour, minute, (fractional) second, and UTC offset.  Other fields, like
1546
// weekday (%a or %A), while parsed for syntactic validity, are ignored
1547
// in the conversion.
1548
//
1549
// Date and time fields that are out-of-range will be treated as errors
1550
// rather than normalizing them like `absl::CivilSecond` does.  For example,
1551
// it is an error to parse the date "Oct 32, 2013" because 32 is out of range.
1552
//
1553
// A leap second of ":60" is normalized to ":00" of the following minute
1554
// with fractional seconds discarded.  The following table shows how the
1555
// given seconds and subseconds will be parsed:
1556
//
1557
//   "59.x" -> 59.x  // exact
1558
//   "60.x" -> 00.0  // normalized
1559
//   "00.x" -> 00.x  // exact
1560
//
1561
// Errors are indicated by returning false and assigning an error message
1562
// to the "err" out param if it is non-null.
1563
//
1564
// Note: If the input string is exactly "infinite-future", the returned
1565
// `absl::Time` will be `absl::InfiniteFuture()` and `true` will be returned.
1566
// If the input string is "infinite-past", the returned `absl::Time` will be
1567
// `absl::InfinitePast()` and `true` will be returned.
1568
//
1569
bool ParseTime(absl::string_view format, absl::string_view input, Time* time,
1570
               std::string* err);
1571
1572
// Like ParseTime() above, but if the format string does not contain a UTC
1573
// offset specification (%z/%Ez/%E*z) then the input is interpreted in the
1574
// given TimeZone.  This means that the input, by itself, does not identify a
1575
// unique instant.  Being time-zone dependent, it also admits the possibility
1576
// of ambiguity or non-existence, in which case the "pre" time (as defined
1577
// by TimeZone::TimeInfo) is returned.  For these reasons we recommend that
1578
// all date/time strings include a UTC offset so they're context independent.
1579
bool ParseTime(absl::string_view format, absl::string_view input, TimeZone tz,
1580
               Time* time, std::string* err);
1581
1582
// ============================================================================
1583
// Implementation Details Follow
1584
// ============================================================================
1585
1586
namespace time_internal {
1587
1588
// Creates a Duration with a given representation.
1589
// REQUIRES: hi,lo is a valid representation of a Duration as specified
1590
// in time/duration.cc.
1591
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeDuration(int64_t hi,
1592
0
                                                              uint32_t lo = 0) {
1593
0
  return Duration(hi, lo);
1594
0
}
1595
1596
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeDuration(int64_t hi,
1597
0
                                                              int64_t lo) {
1598
0
  return MakeDuration(hi, static_cast<uint32_t>(lo));
1599
0
}
1600
1601
// Make a Duration value from a floating-point number, as long as that number
1602
// is in the range [ 0 .. numeric_limits<int64_t>::max ), that is, as long as
1603
// it's positive and can be converted to int64_t without risk of UB.
1604
0
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration MakePosDoubleDuration(double n) {
1605
0
  const int64_t int_secs = static_cast<int64_t>(n);
1606
0
  const uint32_t ticks = static_cast<uint32_t>(
1607
0
      std::round((n - static_cast<double>(int_secs)) * kTicksPerSecond));
1608
0
  return ticks < kTicksPerSecond
1609
0
             ? MakeDuration(int_secs, ticks)
1610
0
             : MakeDuration(int_secs + 1, ticks - kTicksPerSecond);
1611
0
}
1612
1613
// Creates a normalized Duration from an almost-normalized (sec,ticks)
1614
// pair. sec may be positive or negative.  ticks must be in the range
1615
// -kTicksPerSecond < *ticks < kTicksPerSecond.  If ticks is negative it
1616
// will be normalized to a positive value in the resulting Duration.
1617
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeNormalizedDuration(
1618
0
    int64_t sec, int64_t ticks) {
1619
0
  return (ticks < 0) ? MakeDuration(sec - 1, ticks + kTicksPerSecond)
1620
0
                     : MakeDuration(sec, ticks);
1621
0
}
1622
1623
// Provide access to the Duration representation.
1624
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t GetRepHi(Duration d) {
1625
0
  return d.rep_hi_.Get();
1626
0
}
1627
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr uint32_t GetRepLo(Duration d) {
1628
0
  return d.rep_lo_;
1629
0
}
1630
1631
// Returns true iff d is positive or negative infinity.
1632
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool IsInfiniteDuration(Duration d) {
1633
0
  return GetRepLo(d) == ~uint32_t{0};
1634
0
}
1635
1636
// Returns an infinite Duration with the opposite sign.
1637
// REQUIRES: IsInfiniteDuration(d)
1638
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration OppositeInfinity(Duration d) {
1639
0
  return GetRepHi(d) < 0
1640
0
             ? MakeDuration((std::numeric_limits<int64_t>::max)(), ~uint32_t{0})
1641
0
             : MakeDuration((std::numeric_limits<int64_t>::min)(),
1642
0
                            ~uint32_t{0});
1643
0
}
1644
1645
// Returns (-n)-1 (equivalently -(n+1)) without avoidable overflow.
1646
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t NegateAndSubtractOne(
1647
0
    int64_t n) {
1648
  // Note: Good compilers will optimize this expression to ~n when using
1649
  // a two's-complement representation (which is required for int64_t).
1650
0
  return (n < 0) ? -(n + 1) : (-n) - 1;
1651
0
}
1652
1653
// Map between a Time and a Duration since the Unix epoch.  Note that these
1654
// functions depend on the above mentioned choice of the Unix epoch for the
1655
// Time representation (and both need to be Time friends).  Without this
1656
// knowledge, we would need to add-in/subtract-out UnixEpoch() respectively.
1657
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixDuration(Duration d) {
1658
0
  return Time(d);
1659
0
}
1660
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration ToUnixDuration(Time t) {
1661
0
  return t.rep_;
1662
0
}
1663
1664
template <std::intmax_t N>
1665
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
1666
0
                                                           std::ratio<1, N>) {
1667
0
  static_assert(0 < N && N <= 1000 * 1000 * 1000, "Unsupported ratio");
1668
  // Subsecond ratios cannot overflow.
1669
0
  return MakeNormalizedDuration(
1670
0
      v / N, v % N * kTicksPerNanosecond * 1000 * 1000 * 1000 / N);
1671
0
}
Unexecuted instantiation: absl::Duration absl::time_internal::FromInt64<1000000000l>(long, std::__1::ratio<1l, 1000000000l>)
Unexecuted instantiation: absl::Duration absl::time_internal::FromInt64<1000000l>(long, std::__1::ratio<1l, 1000000l>)
Unexecuted instantiation: absl::Duration absl::time_internal::FromInt64<1000l>(long, std::__1::ratio<1l, 1000l>)
Unexecuted instantiation: absl::Duration absl::time_internal::FromInt64<1l>(long, std::__1::ratio<1l, 1l>)
1672
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
1673
0
                                                           std::ratio<60>) {
1674
0
  return (v <= (std::numeric_limits<int64_t>::max)() / 60 &&
1675
0
          v >= (std::numeric_limits<int64_t>::min)() / 60)
1676
0
             ? MakeDuration(v * 60)
1677
0
         : v > 0 ? InfiniteDuration()
1678
0
                 : -InfiniteDuration();
1679
0
}
1680
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
1681
0
                                                           std::ratio<3600>) {
1682
0
  return (v <= (std::numeric_limits<int64_t>::max)() / 3600 &&
1683
0
          v >= (std::numeric_limits<int64_t>::min)() / 3600)
1684
0
             ? MakeDuration(v * 3600)
1685
0
         : v > 0 ? InfiniteDuration()
1686
0
                 : -InfiniteDuration();
1687
0
}
1688
1689
// IsValidRep64<T>(0) is true if the expression `int64_t{std::declval<T>()}` is
1690
// valid. That is, if a T can be assigned to an int64_t without narrowing.
1691
template <typename T>
1692
0
constexpr auto IsValidRep64(int) -> decltype(int64_t{std::declval<T>()} == 0) {
1693
0
  return true;
1694
0
}
Unexecuted instantiation: _ZN4absl13time_internal12IsValidRep64IxEEDTeqtllclsr3stdE7declvalIT_EEELi0EEi
Unexecuted instantiation: _ZN4absl13time_internal12IsValidRep64IlEEDTeqtllclsr3stdE7declvalIT_EEELi0EEi
1695
template <typename T>
1696
constexpr auto IsValidRep64(char) -> bool {
1697
  return false;
1698
}
1699
1700
// Converts a std::chrono::duration to an absl::Duration.
1701
template <typename Rep, typename Period>
1702
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1703
0
    const std::chrono::duration<Rep, Period>& d) {
1704
0
  static_assert(IsValidRep64<Rep>(0), "duration::rep is invalid");
1705
0
  return FromInt64(int64_t{d.count()}, Period{});
1706
0
}
Unexecuted instantiation: absl::Duration absl::time_internal::FromChrono<long long, std::__1::ratio<1l, 1000000000l> >(std::__1::chrono::duration<long long, std::__1::ratio<1l, 1000000000l> > const&)
Unexecuted instantiation: absl::Duration absl::time_internal::FromChrono<long long, std::__1::ratio<1l, 1000000l> >(std::__1::chrono::duration<long long, std::__1::ratio<1l, 1000000l> > const&)
Unexecuted instantiation: absl::Duration absl::time_internal::FromChrono<long long, std::__1::ratio<1l, 1000l> >(std::__1::chrono::duration<long long, std::__1::ratio<1l, 1000l> > const&)
Unexecuted instantiation: absl::Duration absl::time_internal::FromChrono<long long, std::__1::ratio<1l, 1l> >(std::__1::chrono::duration<long long, std::__1::ratio<1l, 1l> > const&)
Unexecuted instantiation: absl::Duration absl::time_internal::FromChrono<long, std::__1::ratio<60l, 1l> >(std::__1::chrono::duration<long, std::__1::ratio<60l, 1l> > const&)
Unexecuted instantiation: absl::Duration absl::time_internal::FromChrono<long, std::__1::ratio<3600l, 1l> >(std::__1::chrono::duration<long, std::__1::ratio<3600l, 1l> > const&)
1707
1708
template <typename Ratio>
1709
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64(Duration d, Ratio) {
1710
  // Note: This may be used on MSVC, which may have a system_clock period of
1711
  // std::ratio<1, 10 * 1000 * 1000>
1712
  return ToInt64Seconds(d * Ratio::den / Ratio::num);
1713
}
1714
// Fastpath implementations for the 6 common duration units.
1715
0
ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d, std::nano) {
1716
0
  return ToInt64Nanoseconds(d);
1717
0
}
1718
0
ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d, std::micro) {
1719
0
  return ToInt64Microseconds(d);
1720
0
}
1721
0
ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d, std::milli) {
1722
0
  return ToInt64Milliseconds(d);
1723
0
}
1724
ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d,
1725
0
                                                     std::ratio<1>) {
1726
0
  return ToInt64Seconds(d);
1727
0
}
1728
ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d,
1729
0
                                                     std::ratio<60>) {
1730
0
  return ToInt64Minutes(d);
1731
0
}
1732
ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d,
1733
0
                                                     std::ratio<3600>) {
1734
0
  return ToInt64Hours(d);
1735
0
}
1736
1737
// Converts an absl::Duration to a chrono duration of type T.
1738
template <typename T>
1739
0
ABSL_ATTRIBUTE_CONST_FUNCTION T ToChronoDuration(Duration d) {
1740
0
  using Rep = typename T::rep;
1741
0
  using Period = typename T::period;
1742
0
  static_assert(IsValidRep64<Rep>(0), "duration::rep is invalid");
1743
0
  if (time_internal::IsInfiniteDuration(d))
1744
0
    return d < ZeroDuration() ? (T::min)() : (T::max)();
1745
0
  const auto v = ToInt64(d, Period{});
1746
0
  if (v > (std::numeric_limits<Rep>::max)()) return (T::max)();
1747
0
  if (v < (std::numeric_limits<Rep>::min)()) return (T::min)();
1748
0
  return T{v};
1749
0
}
Unexecuted instantiation: std::__1::chrono::duration<long long, std::__1::ratio<1l, 1000000000l> > absl::time_internal::ToChronoDuration<std::__1::chrono::duration<long long, std::__1::ratio<1l, 1000000000l> > >(absl::Duration)
Unexecuted instantiation: std::__1::chrono::duration<long long, std::__1::ratio<1l, 1000000l> > absl::time_internal::ToChronoDuration<std::__1::chrono::duration<long long, std::__1::ratio<1l, 1000000l> > >(absl::Duration)
Unexecuted instantiation: std::__1::chrono::duration<long long, std::__1::ratio<1l, 1000l> > absl::time_internal::ToChronoDuration<std::__1::chrono::duration<long long, std::__1::ratio<1l, 1000l> > >(absl::Duration)
Unexecuted instantiation: std::__1::chrono::duration<long long, std::__1::ratio<1l, 1l> > absl::time_internal::ToChronoDuration<std::__1::chrono::duration<long long, std::__1::ratio<1l, 1l> > >(absl::Duration)
Unexecuted instantiation: std::__1::chrono::duration<long, std::__1::ratio<60l, 1l> > absl::time_internal::ToChronoDuration<std::__1::chrono::duration<long, std::__1::ratio<60l, 1l> > >(absl::Duration)
Unexecuted instantiation: std::__1::chrono::duration<long, std::__1::ratio<3600l, 1l> > absl::time_internal::ToChronoDuration<std::__1::chrono::duration<long, std::__1::ratio<3600l, 1l> > >(absl::Duration)
1750
1751
}  // namespace time_internal
1752
1753
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<(Duration lhs,
1754
0
                                                       Duration rhs) {
1755
0
  return time_internal::GetRepHi(lhs) != time_internal::GetRepHi(rhs)
1756
0
             ? time_internal::GetRepHi(lhs) < time_internal::GetRepHi(rhs)
1757
0
         : time_internal::GetRepHi(lhs) == (std::numeric_limits<int64_t>::min)()
1758
0
             ? time_internal::GetRepLo(lhs) + 1 <
1759
0
                   time_internal::GetRepLo(rhs) + 1
1760
0
             : time_internal::GetRepLo(lhs) < time_internal::GetRepLo(rhs);
1761
0
}
1762
1763
#ifdef ABSL_INTERNAL_TIME_HAS_THREE_WAY_COMPARISON
1764
1765
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr std::strong_ordering operator<=>(
1766
    Duration lhs, Duration rhs) {
1767
  const int64_t lhs_hi = time_internal::GetRepHi(lhs);
1768
  const int64_t rhs_hi = time_internal::GetRepHi(rhs);
1769
  if (auto c = lhs_hi <=> rhs_hi; c != std::strong_ordering::equal) {
1770
    return c;
1771
  }
1772
  const uint32_t lhs_lo = time_internal::GetRepLo(lhs);
1773
  const uint32_t rhs_lo = time_internal::GetRepLo(rhs);
1774
  return (lhs_hi == (std::numeric_limits<int64_t>::min)())
1775
             ? (lhs_lo + 1) <=> (rhs_lo + 1)
1776
             : lhs_lo <=> rhs_lo;
1777
}
1778
1779
#endif  // ABSL_INTERNAL_TIME_HAS_THREE_WAY_COMPARISON
1780
1781
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator==(Duration lhs,
1782
0
                                                        Duration rhs) {
1783
0
  return time_internal::GetRepHi(lhs) == time_internal::GetRepHi(rhs) &&
1784
0
         time_internal::GetRepLo(lhs) == time_internal::GetRepLo(rhs);
1785
0
}
1786
1787
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration operator-(Duration d) {
1788
  // This is a little interesting because of the special cases.
1789
  //
1790
  // If rep_lo_ is zero, we have it easy; it's safe to negate rep_hi_, we're
1791
  // dealing with an integral number of seconds, and the only special case is
1792
  // the maximum negative finite duration, which can't be negated.
1793
  //
1794
  // Infinities stay infinite, and just change direction.
1795
  //
1796
  // Finally we're in the case where rep_lo_ is non-zero, and we can borrow
1797
  // a second's worth of ticks and avoid overflow (as negating int64_t-min + 1
1798
  // is safe).
1799
0
  return time_internal::GetRepLo(d) == 0
1800
0
             ? time_internal::GetRepHi(d) ==
1801
0
                       (std::numeric_limits<int64_t>::min)()
1802
0
                   ? InfiniteDuration()
1803
0
                   : time_internal::MakeDuration(-time_internal::GetRepHi(d))
1804
0
         : time_internal::IsInfiniteDuration(d)
1805
0
             ? time_internal::OppositeInfinity(d)
1806
0
             : time_internal::MakeDuration(
1807
0
                   time_internal::NegateAndSubtractOne(
1808
0
                       time_internal::GetRepHi(d)),
1809
0
                   time_internal::kTicksPerSecond - time_internal::GetRepLo(d));
1810
0
}
1811
1812
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration InfiniteDuration() {
1813
0
  return time_internal::MakeDuration((std::numeric_limits<int64_t>::max)(),
1814
0
                                     ~uint32_t{0});
1815
0
}
1816
1817
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1818
0
    const std::chrono::nanoseconds& d) {
1819
0
  return time_internal::FromChrono(d);
1820
0
}
1821
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1822
0
    const std::chrono::microseconds& d) {
1823
0
  return time_internal::FromChrono(d);
1824
0
}
1825
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1826
0
    const std::chrono::milliseconds& d) {
1827
0
  return time_internal::FromChrono(d);
1828
0
}
1829
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1830
0
    const std::chrono::seconds& d) {
1831
0
  return time_internal::FromChrono(d);
1832
0
}
1833
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1834
0
    const std::chrono::minutes& d) {
1835
0
  return time_internal::FromChrono(d);
1836
0
}
1837
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1838
0
    const std::chrono::hours& d) {
1839
0
  return time_internal::FromChrono(d);
1840
0
}
1841
1842
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixNanos(int64_t ns) {
1843
0
  return time_internal::FromUnixDuration(Nanoseconds(ns));
1844
0
}
1845
1846
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixMicros(int64_t us) {
1847
0
  return time_internal::FromUnixDuration(Microseconds(us));
1848
0
}
1849
1850
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixMillis(int64_t ms) {
1851
0
  return time_internal::FromUnixDuration(Milliseconds(ms));
1852
0
}
1853
1854
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixSeconds(int64_t s) {
1855
0
  return time_internal::FromUnixDuration(Seconds(s));
1856
0
}
1857
1858
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromTimeT(time_t t) {
1859
0
  return time_internal::FromUnixDuration(Seconds(t));
1860
0
}
1861
1862
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t ToInt64Nanoseconds(Duration d) {
1863
0
  if (time_internal::GetRepHi(d) >= 0 &&
1864
0
      time_internal::GetRepHi(d) >> 33 == 0) {
1865
0
    return (time_internal::GetRepHi(d) * 1000 * 1000 * 1000) +
1866
0
           (time_internal::GetRepLo(d) / time_internal::kTicksPerNanosecond);
1867
0
  } else {
1868
0
    return d / Nanoseconds(1);
1869
0
  }
1870
0
}
1871
1872
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t ToInt64Microseconds(
1873
0
    Duration d) {
1874
0
  if (time_internal::GetRepHi(d) >= 0 &&
1875
0
      time_internal::GetRepHi(d) >> 43 == 0) {
1876
0
    return (time_internal::GetRepHi(d) * 1000 * 1000) +
1877
0
           (time_internal::GetRepLo(d) /
1878
0
            (time_internal::kTicksPerNanosecond * 1000));
1879
0
  } else {
1880
0
    return d / Microseconds(1);
1881
0
  }
1882
0
}
1883
1884
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t ToInt64Milliseconds(
1885
0
    Duration d) {
1886
0
  if (time_internal::GetRepHi(d) >= 0 &&
1887
0
      time_internal::GetRepHi(d) >> 53 == 0) {
1888
0
    return (time_internal::GetRepHi(d) * 1000) +
1889
0
           (time_internal::GetRepLo(d) /
1890
0
            (time_internal::kTicksPerNanosecond * 1000 * 1000));
1891
0
  } else {
1892
0
    return d / Milliseconds(1);
1893
0
  }
1894
0
}
1895
1896
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t ToInt64Seconds(Duration d) {
1897
0
  int64_t hi = time_internal::GetRepHi(d);
1898
0
  if (time_internal::IsInfiniteDuration(d)) return hi;
1899
0
  if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi;
1900
0
  return hi;
1901
0
}
1902
1903
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t ToInt64Minutes(Duration d) {
1904
0
  int64_t hi = time_internal::GetRepHi(d);
1905
0
  if (time_internal::IsInfiniteDuration(d)) return hi;
1906
0
  if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi;
1907
0
  return hi / 60;
1908
0
}
1909
1910
0
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t ToInt64Hours(Duration d) {
1911
0
  int64_t hi = time_internal::GetRepHi(d);
1912
0
  if (time_internal::IsInfiniteDuration(d)) return hi;
1913
0
  if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi;
1914
0
  return hi / (60 * 60);
1915
0
}
1916
1917
ABSL_NAMESPACE_END
1918
}  // namespace absl
1919
1920
#endif  // ABSL_TIME_TIME_H_