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