Coverage Report

Created: 2024-07-23 06:31

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