00001 // Copyright 2017 The Abseil Authors. 00002 // 00003 // Licensed under the Apache License, Version 2.0 (the "License"); 00004 // you may not use this file except in compliance with the License. 00005 // You may obtain a copy of the License at 00006 // 00007 // https://www.apache.org/licenses/LICENSE-2.0 00008 // 00009 // Unless required by applicable law or agreed to in writing, software 00010 // distributed under the License is distributed on an "AS IS" BASIS, 00011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00012 // See the License for the specific language governing permissions and 00013 // limitations under the License. 00014 // 00015 // ----------------------------------------------------------------------------- 00016 // File: time.h 00017 // ----------------------------------------------------------------------------- 00018 // 00019 // This header file defines abstractions for computing with absolute points 00020 // in time, durations of time, and formatting and parsing time within a given 00021 // time zone. The following abstractions are defined: 00022 // 00023 // * `absl::Time` defines an absolute, specific instance in time 00024 // * `absl::Duration` defines a signed, fixed-length span of time 00025 // * `absl::TimeZone` defines geopolitical time zone regions (as collected 00026 // within the IANA Time Zone database (https://www.iana.org/time-zones)). 00027 // 00028 // Note: Absolute times are distinct from civil times, which refer to the 00029 // human-scale time commonly represented by `YYYY-MM-DD hh:mm:ss`. The mapping 00030 // between absolute and civil times can be specified by use of time zones 00031 // (`absl::TimeZone` within this API). That is: 00032 // 00033 // Civil Time = F(Absolute Time, Time Zone) 00034 // Absolute Time = G(Civil Time, Time Zone) 00035 // 00036 // See civil_time.h for abstractions related to constructing and manipulating 00037 // civil time. 00038 // 00039 // Example: 00040 // 00041 // absl::TimeZone nyc; 00042 // // LoadTimeZone() may fail so it's always better to check for success. 00043 // if (!absl::LoadTimeZone("America/New_York", &nyc)) { 00044 // // handle error case 00045 // } 00046 // 00047 // // My flight leaves NYC on Jan 2, 2017 at 03:04:05 00048 // absl::CivilSecond cs(2017, 1, 2, 3, 4, 5); 00049 // absl::Time takeoff = absl::FromCivil(cs, nyc); 00050 // 00051 // absl::Duration flight_duration = absl::Hours(21) + absl::Minutes(35); 00052 // absl::Time landing = takeoff + flight_duration; 00053 // 00054 // absl::TimeZone syd; 00055 // if (!absl::LoadTimeZone("Australia/Sydney", &syd)) { 00056 // // handle error case 00057 // } 00058 // std::string s = absl::FormatTime( 00059 // "My flight will land in Sydney on %Y-%m-%d at %H:%M:%S", 00060 // landing, syd); 00061 00062 #ifndef ABSL_TIME_TIME_H_ 00063 #define ABSL_TIME_TIME_H_ 00064 00065 #if !defined(_MSC_VER) 00066 #include <sys/time.h> 00067 #else 00068 #include <winsock2.h> 00069 #endif 00070 #include <chrono> // NOLINT(build/c++11) 00071 #include <cmath> 00072 #include <cstdint> 00073 #include <ctime> 00074 #include <ostream> 00075 #include <string> 00076 #include <type_traits> 00077 #include <utility> 00078 00079 #include "absl/strings/string_view.h" 00080 #include "absl/time/civil_time.h" 00081 #include "absl/time/internal/cctz/include/cctz/time_zone.h" 00082 00083 namespace absl { 00084 00085 class Duration; // Defined below 00086 class Time; // Defined below 00087 class TimeZone; // Defined below 00088 00089 namespace time_internal { 00090 int64_t IDivDuration(bool satq, Duration num, Duration den, Duration* rem); 00091 constexpr Time FromUnixDuration(Duration d); 00092 constexpr Duration ToUnixDuration(Time t); 00093 constexpr int64_t GetRepHi(Duration d); 00094 constexpr uint32_t GetRepLo(Duration d); 00095 constexpr Duration MakeDuration(int64_t hi, uint32_t lo); 00096 constexpr Duration MakeDuration(int64_t hi, int64_t lo); 00097 inline Duration MakePosDoubleDuration(double n); 00098 constexpr int64_t kTicksPerNanosecond = 4; 00099 constexpr int64_t kTicksPerSecond = 1000 * 1000 * 1000 * kTicksPerNanosecond; 00100 template <std::intmax_t N> 00101 constexpr Duration FromInt64(int64_t v, std::ratio<1, N>); 00102 constexpr Duration FromInt64(int64_t v, std::ratio<60>); 00103 constexpr Duration FromInt64(int64_t v, std::ratio<3600>); 00104 template <typename T> 00105 using EnableIfIntegral = typename std::enable_if< 00106 std::is_integral<T>::value || std::is_enum<T>::value, int>::type; 00107 template <typename T> 00108 using EnableIfFloat = 00109 typename std::enable_if<std::is_floating_point<T>::value, int>::type; 00110 } // namespace time_internal 00111 00112 // Duration 00113 // 00114 // The `absl::Duration` class represents a signed, fixed-length span of time. 00115 // A `Duration` is generated using a unit-specific factory function, or is 00116 // the result of subtracting one `absl::Time` from another. Durations behave 00117 // like unit-safe integers and they support all the natural integer-like 00118 // arithmetic operations. Arithmetic overflows and saturates at +/- infinity. 00119 // `Duration` should be passed by value rather than const reference. 00120 // 00121 // Factory functions `Nanoseconds()`, `Microseconds()`, `Milliseconds()`, 00122 // `Seconds()`, `Minutes()`, `Hours()` and `InfiniteDuration()` allow for 00123 // creation of constexpr `Duration` values 00124 // 00125 // Examples: 00126 // 00127 // constexpr absl::Duration ten_ns = absl::Nanoseconds(10); 00128 // constexpr absl::Duration min = absl::Minutes(1); 00129 // constexpr absl::Duration hour = absl::Hours(1); 00130 // absl::Duration dur = 60 * min; // dur == hour 00131 // absl::Duration half_sec = absl::Milliseconds(500); 00132 // absl::Duration quarter_sec = 0.25 * absl::Seconds(1); 00133 // 00134 // `Duration` values can be easily converted to an integral number of units 00135 // using the division operator. 00136 // 00137 // Example: 00138 // 00139 // constexpr absl::Duration dur = absl::Milliseconds(1500); 00140 // int64_t ns = dur / absl::Nanoseconds(1); // ns == 1500000000 00141 // int64_t ms = dur / absl::Milliseconds(1); // ms == 1500 00142 // int64_t sec = dur / absl::Seconds(1); // sec == 1 (subseconds truncated) 00143 // int64_t min = dur / absl::Minutes(1); // min == 0 00144 // 00145 // See the `IDivDuration()` and `FDivDuration()` functions below for details on 00146 // how to access the fractional parts of the quotient. 00147 // 00148 // Alternatively, conversions can be performed using helpers such as 00149 // `ToInt64Microseconds()` and `ToDoubleSeconds()`. 00150 class Duration { 00151 public: 00152 // Value semantics. 00153 constexpr Duration() : rep_hi_(0), rep_lo_(0) {} // zero-length duration 00154 00155 // Copyable. 00156 #if !defined(__clang__) && defined(_MSC_VER) && _MSC_VER < 1910 00157 // Explicitly defining the constexpr copy constructor avoids an MSVC bug. 00158 constexpr Duration(const Duration& d) 00159 : rep_hi_(d.rep_hi_), rep_lo_(d.rep_lo_) {} 00160 #else 00161 constexpr Duration(const Duration& d) = default; 00162 #endif 00163 Duration& operator=(const Duration& d) = default; 00164 00165 // Compound assignment operators. 00166 Duration& operator+=(Duration d); 00167 Duration& operator-=(Duration d); 00168 Duration& operator*=(int64_t r); 00169 Duration& operator*=(double r); 00170 Duration& operator/=(int64_t r); 00171 Duration& operator/=(double r); 00172 Duration& operator%=(Duration rhs); 00173 00174 // Overloads that forward to either the int64_t or double overloads above. 00175 template <typename T> 00176 Duration& operator*=(T r) { 00177 int64_t x = r; 00178 return *this *= x; 00179 } 00180 template <typename T> 00181 Duration& operator/=(T r) { 00182 int64_t x = r; 00183 return *this /= x; 00184 } 00185 Duration& operator*=(float r) { return *this *= static_cast<double>(r); } 00186 Duration& operator/=(float r) { return *this /= static_cast<double>(r); } 00187 00188 template <typename H> 00189 friend H AbslHashValue(H h, Duration d) { 00190 return H::combine(std::move(h), d.rep_hi_, d.rep_lo_); 00191 } 00192 00193 private: 00194 friend constexpr int64_t time_internal::GetRepHi(Duration d); 00195 friend constexpr uint32_t time_internal::GetRepLo(Duration d); 00196 friend constexpr Duration time_internal::MakeDuration(int64_t hi, 00197 uint32_t lo); 00198 constexpr Duration(int64_t hi, uint32_t lo) : rep_hi_(hi), rep_lo_(lo) {} 00199 int64_t rep_hi_; 00200 uint32_t rep_lo_; 00201 }; 00202 00203 // Relational Operators 00204 constexpr bool operator<(Duration lhs, Duration rhs); 00205 constexpr bool operator>(Duration lhs, Duration rhs) { return rhs < lhs; } 00206 constexpr bool operator>=(Duration lhs, Duration rhs) { return !(lhs < rhs); } 00207 constexpr bool operator<=(Duration lhs, Duration rhs) { return !(rhs < lhs); } 00208 constexpr bool operator==(Duration lhs, Duration rhs); 00209 constexpr bool operator!=(Duration lhs, Duration rhs) { return !(lhs == rhs); } 00210 00211 // Additive Operators 00212 constexpr Duration operator-(Duration d); 00213 inline Duration operator+(Duration lhs, Duration rhs) { return lhs += rhs; } 00214 inline Duration operator-(Duration lhs, Duration rhs) { return lhs -= rhs; } 00215 00216 // Multiplicative Operators 00217 template <typename T> 00218 Duration operator*(Duration lhs, T rhs) { 00219 return lhs *= rhs; 00220 } 00221 template <typename T> 00222 Duration operator*(T lhs, Duration rhs) { 00223 return rhs *= lhs; 00224 } 00225 template <typename T> 00226 Duration operator/(Duration lhs, T rhs) { 00227 return lhs /= rhs; 00228 } 00229 inline int64_t operator/(Duration lhs, Duration rhs) { 00230 return time_internal::IDivDuration(true, lhs, rhs, 00231 &lhs); // trunc towards zero 00232 } 00233 inline Duration operator%(Duration lhs, Duration rhs) { return lhs %= rhs; } 00234 00235 // IDivDuration() 00236 // 00237 // Divides a numerator `Duration` by a denominator `Duration`, returning the 00238 // quotient and remainder. The remainder always has the same sign as the 00239 // numerator. The returned quotient and remainder respect the identity: 00240 // 00241 // numerator = denominator * quotient + remainder 00242 // 00243 // Returned quotients are capped to the range of `int64_t`, with the difference 00244 // spilling into the remainder to uphold the above identity. This means that the 00245 // remainder returned could differ from the remainder returned by 00246 // `Duration::operator%` for huge quotients. 00247 // 00248 // See also the notes on `InfiniteDuration()` below regarding the behavior of 00249 // division involving zero and infinite durations. 00250 // 00251 // Example: 00252 // 00253 // constexpr absl::Duration a = 00254 // absl::Seconds(std::numeric_limits<int64_t>::max()); // big 00255 // constexpr absl::Duration b = absl::Nanoseconds(1); // small 00256 // 00257 // absl::Duration rem = a % b; 00258 // // rem == absl::ZeroDuration() 00259 // 00260 // // Here, q would overflow int64_t, so rem accounts for the difference. 00261 // int64_t q = absl::IDivDuration(a, b, &rem); 00262 // // q == std::numeric_limits<int64_t>::max(), rem == a - b * q 00263 inline int64_t IDivDuration(Duration num, Duration den, Duration* rem) { 00264 return time_internal::IDivDuration(true, num, den, 00265 rem); // trunc towards zero 00266 } 00267 00268 // FDivDuration() 00269 // 00270 // Divides a `Duration` numerator into a fractional number of units of a 00271 // `Duration` denominator. 00272 // 00273 // See also the notes on `InfiniteDuration()` below regarding the behavior of 00274 // division involving zero and infinite durations. 00275 // 00276 // Example: 00277 // 00278 // double d = absl::FDivDuration(absl::Milliseconds(1500), absl::Seconds(1)); 00279 // // d == 1.5 00280 double FDivDuration(Duration num, Duration den); 00281 00282 // ZeroDuration() 00283 // 00284 // Returns a zero-length duration. This function behaves just like the default 00285 // constructor, but the name helps make the semantics clear at call sites. 00286 constexpr Duration ZeroDuration() { return Duration(); } 00287 00288 // AbsDuration() 00289 // 00290 // Returns the absolute value of a duration. 00291 inline Duration AbsDuration(Duration d) { 00292 return (d < ZeroDuration()) ? -d : d; 00293 } 00294 00295 // Trunc() 00296 // 00297 // Truncates a duration (toward zero) to a multiple of a non-zero unit. 00298 // 00299 // Example: 00300 // 00301 // absl::Duration d = absl::Nanoseconds(123456789); 00302 // absl::Duration a = absl::Trunc(d, absl::Microseconds(1)); // 123456us 00303 Duration Trunc(Duration d, Duration unit); 00304 00305 // Floor() 00306 // 00307 // Floors a duration using the passed duration unit to its largest value not 00308 // greater than the duration. 00309 // 00310 // Example: 00311 // 00312 // absl::Duration d = absl::Nanoseconds(123456789); 00313 // absl::Duration b = absl::Floor(d, absl::Microseconds(1)); // 123456us 00314 Duration Floor(Duration d, Duration unit); 00315 00316 // Ceil() 00317 // 00318 // Returns the ceiling of a duration using the passed duration unit to its 00319 // smallest value not less than the duration. 00320 // 00321 // Example: 00322 // 00323 // absl::Duration d = absl::Nanoseconds(123456789); 00324 // absl::Duration c = absl::Ceil(d, absl::Microseconds(1)); // 123457us 00325 Duration Ceil(Duration d, Duration unit); 00326 00327 // InfiniteDuration() 00328 // 00329 // Returns an infinite `Duration`. To get a `Duration` representing negative 00330 // infinity, use `-InfiniteDuration()`. 00331 // 00332 // Duration arithmetic overflows to +/- infinity and saturates. In general, 00333 // arithmetic with `Duration` infinities is similar to IEEE 754 infinities 00334 // except where IEEE 754 NaN would be involved, in which case +/- 00335 // `InfiniteDuration()` is used in place of a "nan" Duration. 00336 // 00337 // Examples: 00338 // 00339 // constexpr absl::Duration inf = absl::InfiniteDuration(); 00340 // const absl::Duration d = ... any finite duration ... 00341 // 00342 // inf == inf + inf 00343 // inf == inf + d 00344 // inf == inf - inf 00345 // -inf == d - inf 00346 // 00347 // inf == d * 1e100 00348 // inf == inf / 2 00349 // 0 == d / inf 00350 // INT64_MAX == inf / d 00351 // 00352 // d < inf 00353 // -inf < d 00354 // 00355 // // Division by zero returns infinity, or INT64_MIN/MAX where appropriate. 00356 // inf == d / 0 00357 // INT64_MAX == d / absl::ZeroDuration() 00358 // 00359 // The examples involving the `/` operator above also apply to `IDivDuration()` 00360 // and `FDivDuration()`. 00361 constexpr Duration InfiniteDuration(); 00362 00363 // Nanoseconds() 00364 // Microseconds() 00365 // Milliseconds() 00366 // Seconds() 00367 // Minutes() 00368 // Hours() 00369 // 00370 // Factory functions for constructing `Duration` values from an integral number 00371 // of the unit indicated by the factory function's name. 00372 // 00373 // Note: no "Days()" factory function exists because "a day" is ambiguous. 00374 // Civil days are not always 24 hours long, and a 24-hour duration often does 00375 // not correspond with a civil day. If a 24-hour duration is needed, use 00376 // `absl::Hours(24)`. (If you actually want a civil day, use absl::CivilDay 00377 // from civil_time.h.) 00378 // 00379 // Example: 00380 // 00381 // absl::Duration a = absl::Seconds(60); 00382 // absl::Duration b = absl::Minutes(1); // b == a 00383 constexpr Duration Nanoseconds(int64_t n); 00384 constexpr Duration Microseconds(int64_t n); 00385 constexpr Duration Milliseconds(int64_t n); 00386 constexpr Duration Seconds(int64_t n); 00387 constexpr Duration Minutes(int64_t n); 00388 constexpr Duration Hours(int64_t n); 00389 00390 // Factory overloads for constructing `Duration` values from a floating-point 00391 // number of the unit indicated by the factory function's name. These functions 00392 // exist for convenience, but they are not as efficient as the integral 00393 // factories, which should be preferred. 00394 // 00395 // Example: 00396 // 00397 // auto a = absl::Seconds(1.5); // OK 00398 // auto b = absl::Milliseconds(1500); // BETTER 00399 template <typename T, time_internal::EnableIfFloat<T> = 0> 00400 Duration Nanoseconds(T n) { 00401 return n * Nanoseconds(1); 00402 } 00403 template <typename T, time_internal::EnableIfFloat<T> = 0> 00404 Duration Microseconds(T n) { 00405 return n * Microseconds(1); 00406 } 00407 template <typename T, time_internal::EnableIfFloat<T> = 0> 00408 Duration Milliseconds(T n) { 00409 return n * Milliseconds(1); 00410 } 00411 template <typename T, time_internal::EnableIfFloat<T> = 0> 00412 Duration Seconds(T n) { 00413 if (n >= 0) { // Note: `NaN >= 0` is false. 00414 if (n >= (std::numeric_limits<int64_t>::max)()) return InfiniteDuration(); 00415 return time_internal::MakePosDoubleDuration(n); 00416 } else { 00417 if (std::isnan(n)) 00418 return std::signbit(n) ? -InfiniteDuration() : InfiniteDuration(); 00419 if (n <= (std::numeric_limits<int64_t>::min)()) return -InfiniteDuration(); 00420 return -time_internal::MakePosDoubleDuration(-n); 00421 } 00422 } 00423 template <typename T, time_internal::EnableIfFloat<T> = 0> 00424 Duration Minutes(T n) { 00425 return n * Minutes(1); 00426 } 00427 template <typename T, time_internal::EnableIfFloat<T> = 0> 00428 Duration Hours(T n) { 00429 return n * Hours(1); 00430 } 00431 00432 // ToInt64Nanoseconds() 00433 // ToInt64Microseconds() 00434 // ToInt64Milliseconds() 00435 // ToInt64Seconds() 00436 // ToInt64Minutes() 00437 // ToInt64Hours() 00438 // 00439 // Helper functions that convert a Duration to an integral count of the 00440 // indicated unit. These functions are shorthand for the `IDivDuration()` 00441 // function above; see its documentation for details about overflow, etc. 00442 // 00443 // Example: 00444 // 00445 // absl::Duration d = absl::Milliseconds(1500); 00446 // int64_t isec = absl::ToInt64Seconds(d); // isec == 1 00447 int64_t ToInt64Nanoseconds(Duration d); 00448 int64_t ToInt64Microseconds(Duration d); 00449 int64_t ToInt64Milliseconds(Duration d); 00450 int64_t ToInt64Seconds(Duration d); 00451 int64_t ToInt64Minutes(Duration d); 00452 int64_t ToInt64Hours(Duration d); 00453 00454 // ToDoubleNanoSeconds() 00455 // ToDoubleMicroseconds() 00456 // ToDoubleMilliseconds() 00457 // ToDoubleSeconds() 00458 // ToDoubleMinutes() 00459 // ToDoubleHours() 00460 // 00461 // Helper functions that convert a Duration to a floating point count of the 00462 // indicated unit. These functions are shorthand for the `FDivDuration()` 00463 // function above; see its documentation for details about overflow, etc. 00464 // 00465 // Example: 00466 // 00467 // absl::Duration d = absl::Milliseconds(1500); 00468 // double dsec = absl::ToDoubleSeconds(d); // dsec == 1.5 00469 double ToDoubleNanoseconds(Duration d); 00470 double ToDoubleMicroseconds(Duration d); 00471 double ToDoubleMilliseconds(Duration d); 00472 double ToDoubleSeconds(Duration d); 00473 double ToDoubleMinutes(Duration d); 00474 double ToDoubleHours(Duration d); 00475 00476 // FromChrono() 00477 // 00478 // Converts any of the pre-defined std::chrono durations to an absl::Duration. 00479 // 00480 // Example: 00481 // 00482 // std::chrono::milliseconds ms(123); 00483 // absl::Duration d = absl::FromChrono(ms); 00484 constexpr Duration FromChrono(const std::chrono::nanoseconds& d); 00485 constexpr Duration FromChrono(const std::chrono::microseconds& d); 00486 constexpr Duration FromChrono(const std::chrono::milliseconds& d); 00487 constexpr Duration FromChrono(const std::chrono::seconds& d); 00488 constexpr Duration FromChrono(const std::chrono::minutes& d); 00489 constexpr Duration FromChrono(const std::chrono::hours& d); 00490 00491 // ToChronoNanoseconds() 00492 // ToChronoMicroseconds() 00493 // ToChronoMilliseconds() 00494 // ToChronoSeconds() 00495 // ToChronoMinutes() 00496 // ToChronoHours() 00497 // 00498 // Converts an absl::Duration to any of the pre-defined std::chrono durations. 00499 // If overflow would occur, the returned value will saturate at the min/max 00500 // chrono duration value instead. 00501 // 00502 // Example: 00503 // 00504 // absl::Duration d = absl::Microseconds(123); 00505 // auto x = absl::ToChronoMicroseconds(d); 00506 // auto y = absl::ToChronoNanoseconds(d); // x == y 00507 // auto z = absl::ToChronoSeconds(absl::InfiniteDuration()); 00508 // // z == std::chrono::seconds::max() 00509 std::chrono::nanoseconds ToChronoNanoseconds(Duration d); 00510 std::chrono::microseconds ToChronoMicroseconds(Duration d); 00511 std::chrono::milliseconds ToChronoMilliseconds(Duration d); 00512 std::chrono::seconds ToChronoSeconds(Duration d); 00513 std::chrono::minutes ToChronoMinutes(Duration d); 00514 std::chrono::hours ToChronoHours(Duration d); 00515 00516 // FormatDuration() 00517 // 00518 // Returns a string representing the duration in the form "72h3m0.5s". 00519 // Returns "inf" or "-inf" for +/- `InfiniteDuration()`. 00520 std::string FormatDuration(Duration d); 00521 00522 // Output stream operator. 00523 inline std::ostream& operator<<(std::ostream& os, Duration d) { 00524 return os << FormatDuration(d); 00525 } 00526 00527 // ParseDuration() 00528 // 00529 // Parses a duration string consisting of a possibly signed sequence of 00530 // decimal numbers, each with an optional fractional part and a unit 00531 // suffix. The valid suffixes are "ns", "us" "ms", "s", "m", and "h". 00532 // Simple examples include "300ms", "-1.5h", and "2h45m". Parses "0" as 00533 // `ZeroDuration()`. Parses "inf" and "-inf" as +/- `InfiniteDuration()`. 00534 bool ParseDuration(const std::string& dur_string, Duration* d); 00535 00536 // Support for flag values of type Duration. Duration flags must be specified 00537 // in a format that is valid input for absl::ParseDuration(). 00538 bool ParseFlag(const std::string& text, Duration* dst, std::string* error); 00539 std::string UnparseFlag(Duration d); 00540 00541 // Time 00542 // 00543 // An `absl::Time` represents a specific instant in time. Arithmetic operators 00544 // are provided for naturally expressing time calculations. Instances are 00545 // created using `absl::Now()` and the `absl::From*()` factory functions that 00546 // accept the gamut of other time representations. Formatting and parsing 00547 // functions are provided for conversion to and from strings. `absl::Time` 00548 // should be passed by value rather than const reference. 00549 // 00550 // `absl::Time` assumes there are 60 seconds in a minute, which means the 00551 // underlying time scales must be "smeared" to eliminate leap seconds. 00552 // See https://developers.google.com/time/smear. 00553 // 00554 // Even though `absl::Time` supports a wide range of timestamps, exercise 00555 // caution when using values in the distant past. `absl::Time` uses the 00556 // Proleptic Gregorian calendar, which extends the Gregorian calendar backward 00557 // to dates before its introduction in 1582. 00558 // See https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar 00559 // for more information. Use the ICU calendar classes to convert a date in 00560 // some other calendar (http://userguide.icu-project.org/datetime/calendar). 00561 // 00562 // Similarly, standardized time zones are a reasonably recent innovation, with 00563 // the Greenwich prime meridian being established in 1884. The TZ database 00564 // itself does not profess accurate offsets for timestamps prior to 1970. The 00565 // breakdown of future timestamps is subject to the whim of regional 00566 // governments. 00567 // 00568 // The `absl::Time` class represents an instant in time as a count of clock 00569 // ticks of some granularity (resolution) from some starting point (epoch). 00570 // 00571 // `absl::Time` uses a resolution that is high enough to avoid loss in 00572 // precision, and a range that is wide enough to avoid overflow, when 00573 // converting between tick counts in most Google time scales (i.e., resolution 00574 // of at least one nanosecond, and range +/-100 billion years). Conversions 00575 // between the time scales are performed by truncating (towards negative 00576 // infinity) to the nearest representable point. 00577 // 00578 // Examples: 00579 // 00580 // absl::Time t1 = ...; 00581 // absl::Time t2 = t1 + absl::Minutes(2); 00582 // absl::Duration d = t2 - t1; // == absl::Minutes(2) 00583 // 00584 class Time { 00585 public: 00586 // Value semantics. 00587 00588 // Returns the Unix epoch. However, those reading your code may not know 00589 // or expect the Unix epoch as the default value, so make your code more 00590 // readable by explicitly initializing all instances before use. 00591 // 00592 // Example: 00593 // absl::Time t = absl::UnixEpoch(); 00594 // absl::Time t = absl::Now(); 00595 // absl::Time t = absl::TimeFromTimeval(tv); 00596 // absl::Time t = absl::InfinitePast(); 00597 constexpr Time() = default; 00598 00599 // Copyable. 00600 constexpr Time(const Time& t) = default; 00601 Time& operator=(const Time& t) = default; 00602 00603 // Assignment operators. 00604 Time& operator+=(Duration d) { 00605 rep_ += d; 00606 return *this; 00607 } 00608 Time& operator-=(Duration d) { 00609 rep_ -= d; 00610 return *this; 00611 } 00612 00613 // Time::Breakdown 00614 // 00615 // The calendar and wall-clock (aka "civil time") components of an 00616 // `absl::Time` in a certain `absl::TimeZone`. This struct is not 00617 // intended to represent an instant in time. So, rather than passing 00618 // a `Time::Breakdown` to a function, pass an `absl::Time` and an 00619 // `absl::TimeZone`. 00620 // 00621 // Deprecated. Use `absl::TimeZone::CivilInfo`. 00622 struct 00623 Breakdown { 00624 int64_t year; // year (e.g., 2013) 00625 int month; // month of year [1:12] 00626 int day; // day of month [1:31] 00627 int hour; // hour of day [0:23] 00628 int minute; // minute of hour [0:59] 00629 int second; // second of minute [0:59] 00630 Duration subsecond; // [Seconds(0):Seconds(1)) if finite 00631 int weekday; // 1==Mon, ..., 7=Sun 00632 int yearday; // day of year [1:366] 00633 00634 // Note: The following fields exist for backward compatibility 00635 // with older APIs. Accessing these fields directly is a sign of 00636 // imprudent logic in the calling code. Modern time-related code 00637 // should only access this data indirectly by way of FormatTime(). 00638 // These fields are undefined for InfiniteFuture() and InfinitePast(). 00639 int offset; // seconds east of UTC 00640 bool is_dst; // is offset non-standard? 00641 const char* zone_abbr; // time-zone abbreviation (e.g., "PST") 00642 }; 00643 00644 // Time::In() 00645 // 00646 // Returns the breakdown of this instant in the given TimeZone. 00647 // 00648 // Deprecated. Use `absl::TimeZone::At(Time)`. 00649 Breakdown In(TimeZone tz) const; 00650 00651 template <typename H> 00652 friend H AbslHashValue(H h, Time t) { 00653 return H::combine(std::move(h), t.rep_); 00654 } 00655 00656 private: 00657 friend constexpr Time time_internal::FromUnixDuration(Duration d); 00658 friend constexpr Duration time_internal::ToUnixDuration(Time t); 00659 friend constexpr bool operator<(Time lhs, Time rhs); 00660 friend constexpr bool operator==(Time lhs, Time rhs); 00661 friend Duration operator-(Time lhs, Time rhs); 00662 friend constexpr Time UniversalEpoch(); 00663 friend constexpr Time InfiniteFuture(); 00664 friend constexpr Time InfinitePast(); 00665 constexpr explicit Time(Duration rep) : rep_(rep) {} 00666 Duration rep_; 00667 }; 00668 00669 // Relational Operators 00670 constexpr bool operator<(Time lhs, Time rhs) { return lhs.rep_ < rhs.rep_; } 00671 constexpr bool operator>(Time lhs, Time rhs) { return rhs < lhs; } 00672 constexpr bool operator>=(Time lhs, Time rhs) { return !(lhs < rhs); } 00673 constexpr bool operator<=(Time lhs, Time rhs) { return !(rhs < lhs); } 00674 constexpr bool operator==(Time lhs, Time rhs) { return lhs.rep_ == rhs.rep_; } 00675 constexpr bool operator!=(Time lhs, Time rhs) { return !(lhs == rhs); } 00676 00677 // Additive Operators 00678 inline Time operator+(Time lhs, Duration rhs) { return lhs += rhs; } 00679 inline Time operator+(Duration lhs, Time rhs) { return rhs += lhs; } 00680 inline Time operator-(Time lhs, Duration rhs) { return lhs -= rhs; } 00681 inline Duration operator-(Time lhs, Time rhs) { return lhs.rep_ - rhs.rep_; } 00682 00683 // UnixEpoch() 00684 // 00685 // Returns the `absl::Time` representing "1970-01-01 00:00:00.0 +0000". 00686 constexpr Time UnixEpoch() { return Time(); } 00687 00688 // UniversalEpoch() 00689 // 00690 // Returns the `absl::Time` representing "0001-01-01 00:00:00.0 +0000", the 00691 // epoch of the ICU Universal Time Scale. 00692 constexpr Time UniversalEpoch() { 00693 // 719162 is the number of days from 0001-01-01 to 1970-01-01, 00694 // assuming the Gregorian calendar. 00695 return Time(time_internal::MakeDuration(-24 * 719162 * int64_t{3600}, 0U)); 00696 } 00697 00698 // InfiniteFuture() 00699 // 00700 // Returns an `absl::Time` that is infinitely far in the future. 00701 constexpr Time InfiniteFuture() { 00702 return Time( 00703 time_internal::MakeDuration((std::numeric_limits<int64_t>::max)(), ~0U)); 00704 } 00705 00706 // InfinitePast() 00707 // 00708 // Returns an `absl::Time` that is infinitely far in the past. 00709 constexpr Time InfinitePast() { 00710 return Time( 00711 time_internal::MakeDuration((std::numeric_limits<int64_t>::min)(), ~0U)); 00712 } 00713 00714 // FromUnixNanos() 00715 // FromUnixMicros() 00716 // FromUnixMillis() 00717 // FromUnixSeconds() 00718 // FromTimeT() 00719 // FromUDate() 00720 // FromUniversal() 00721 // 00722 // Creates an `absl::Time` from a variety of other representations. 00723 constexpr Time FromUnixNanos(int64_t ns); 00724 constexpr Time FromUnixMicros(int64_t us); 00725 constexpr Time FromUnixMillis(int64_t ms); 00726 constexpr Time FromUnixSeconds(int64_t s); 00727 constexpr Time FromTimeT(time_t t); 00728 Time FromUDate(double udate); 00729 Time FromUniversal(int64_t universal); 00730 00731 // ToUnixNanos() 00732 // ToUnixMicros() 00733 // ToUnixMillis() 00734 // ToUnixSeconds() 00735 // ToTimeT() 00736 // ToUDate() 00737 // ToUniversal() 00738 // 00739 // Converts an `absl::Time` to a variety of other representations. Note that 00740 // these operations round down toward negative infinity where necessary to 00741 // adjust to the resolution of the result type. Beware of possible time_t 00742 // over/underflow in ToTime{T,val,spec}() on 32-bit platforms. 00743 int64_t ToUnixNanos(Time t); 00744 int64_t ToUnixMicros(Time t); 00745 int64_t ToUnixMillis(Time t); 00746 int64_t ToUnixSeconds(Time t); 00747 time_t ToTimeT(Time t); 00748 double ToUDate(Time t); 00749 int64_t ToUniversal(Time t); 00750 00751 // DurationFromTimespec() 00752 // DurationFromTimeval() 00753 // ToTimespec() 00754 // ToTimeval() 00755 // TimeFromTimespec() 00756 // TimeFromTimeval() 00757 // ToTimespec() 00758 // ToTimeval() 00759 // 00760 // Some APIs use a timespec or a timeval as a Duration (e.g., nanosleep(2) 00761 // and select(2)), while others use them as a Time (e.g. clock_gettime(2) 00762 // and gettimeofday(2)), so conversion functions are provided for both cases. 00763 // The "to timespec/val" direction is easily handled via overloading, but 00764 // for "from timespec/val" the desired type is part of the function name. 00765 Duration DurationFromTimespec(timespec ts); 00766 Duration DurationFromTimeval(timeval tv); 00767 timespec ToTimespec(Duration d); 00768 timeval ToTimeval(Duration d); 00769 Time TimeFromTimespec(timespec ts); 00770 Time TimeFromTimeval(timeval tv); 00771 timespec ToTimespec(Time t); 00772 timeval ToTimeval(Time t); 00773 00774 // FromChrono() 00775 // 00776 // Converts a std::chrono::system_clock::time_point to an absl::Time. 00777 // 00778 // Example: 00779 // 00780 // auto tp = std::chrono::system_clock::from_time_t(123); 00781 // absl::Time t = absl::FromChrono(tp); 00782 // // t == absl::FromTimeT(123) 00783 Time FromChrono(const std::chrono::system_clock::time_point& tp); 00784 00785 // ToChronoTime() 00786 // 00787 // Converts an absl::Time to a std::chrono::system_clock::time_point. If 00788 // overflow would occur, the returned value will saturate at the min/max time 00789 // point value instead. 00790 // 00791 // Example: 00792 // 00793 // absl::Time t = absl::FromTimeT(123); 00794 // auto tp = absl::ToChronoTime(t); 00795 // // tp == std::chrono::system_clock::from_time_t(123); 00796 std::chrono::system_clock::time_point ToChronoTime(Time); 00797 00798 // Support for flag values of type Time. Time flags must be specified in a 00799 // format that matches absl::RFC3339_full. For example: 00800 // 00801 // --start_time=2016-01-02T03:04:05.678+08:00 00802 // 00803 // Note: A UTC offset (or 'Z' indicating a zero-offset from UTC) is required. 00804 // 00805 // Additionally, if you'd like to specify a time as a count of 00806 // seconds/milliseconds/etc from the Unix epoch, use an absl::Duration flag 00807 // and add that duration to absl::UnixEpoch() to get an absl::Time. 00808 bool ParseFlag(const std::string& text, Time* t, std::string* error); 00809 std::string UnparseFlag(Time t); 00810 00811 // TimeZone 00812 // 00813 // The `absl::TimeZone` is an opaque, small, value-type class representing a 00814 // geo-political region within which particular rules are used for converting 00815 // between absolute and civil times (see https://git.io/v59Ly). `absl::TimeZone` 00816 // values are named using the TZ identifiers from the IANA Time Zone Database, 00817 // such as "America/Los_Angeles" or "Australia/Sydney". `absl::TimeZone` values 00818 // are created from factory functions such as `absl::LoadTimeZone()`. Note: 00819 // strings like "PST" and "EDT" are not valid TZ identifiers. Prefer to pass by 00820 // value rather than const reference. 00821 // 00822 // For more on the fundamental concepts of time zones, absolute times, and civil 00823 // times, see https://github.com/google/cctz#fundamental-concepts 00824 // 00825 // Examples: 00826 // 00827 // absl::TimeZone utc = absl::UTCTimeZone(); 00828 // absl::TimeZone pst = absl::FixedTimeZone(-8 * 60 * 60); 00829 // absl::TimeZone loc = absl::LocalTimeZone(); 00830 // absl::TimeZone lax; 00831 // if (!absl::LoadTimeZone("America/Los_Angeles", &lax)) { 00832 // // handle error case 00833 // } 00834 // 00835 // See also: 00836 // - https://github.com/google/cctz 00837 // - https://www.iana.org/time-zones 00838 // - https://en.wikipedia.org/wiki/Zoneinfo 00839 class TimeZone { 00840 public: 00841 explicit TimeZone(time_internal::cctz::time_zone tz) : cz_(tz) {} 00842 TimeZone() = default; // UTC, but prefer UTCTimeZone() to be explicit. 00843 00844 // Copyable. 00845 TimeZone(const TimeZone&) = default; 00846 TimeZone& operator=(const TimeZone&) = default; 00847 00848 explicit operator time_internal::cctz::time_zone() const { return cz_; } 00849 00850 std::string name() const { return cz_.name(); } 00851 00852 // TimeZone::CivilInfo 00853 // 00854 // Information about the civil time corresponding to an absolute time. 00855 // This struct is not intended to represent an instant in time. So, rather 00856 // than passing a `TimeZone::CivilInfo` to a function, pass an `absl::Time` 00857 // and an `absl::TimeZone`. 00858 struct CivilInfo { 00859 CivilSecond cs; 00860 Duration subsecond; 00861 00862 // Note: The following fields exist for backward compatibility 00863 // with older APIs. Accessing these fields directly is a sign of 00864 // imprudent logic in the calling code. Modern time-related code 00865 // should only access this data indirectly by way of FormatTime(). 00866 // These fields are undefined for InfiniteFuture() and InfinitePast(). 00867 int offset; // seconds east of UTC 00868 bool is_dst; // is offset non-standard? 00869 const char* zone_abbr; // time-zone abbreviation (e.g., "PST") 00870 }; 00871 00872 // TimeZone::At(Time) 00873 // 00874 // Returns the civil time for this TimeZone at a certain `absl::Time`. 00875 // If the input time is infinite, the output civil second will be set to 00876 // CivilSecond::max() or min(), and the subsecond will be infinite. 00877 // 00878 // Example: 00879 // 00880 // const auto epoch = lax.At(absl::UnixEpoch()); 00881 // // epoch.cs == 1969-12-31 16:00:00 00882 // // epoch.subsecond == absl::ZeroDuration() 00883 // // epoch.offset == -28800 00884 // // epoch.is_dst == false 00885 // // epoch.abbr == "PST" 00886 CivilInfo At(Time t) const; 00887 00888 // TimeZone::TimeInfo 00889 // 00890 // Information about the absolute times corresponding to a civil time. 00891 // (Subseconds must be handled separately.) 00892 // 00893 // It is possible for a caller to pass a civil-time value that does 00894 // not represent an actual or unique instant in time (due to a shift 00895 // in UTC offset in the TimeZone, which results in a discontinuity in 00896 // the civil-time components). For example, a daylight-saving-time 00897 // transition skips or repeats civil times---in the United States, 00898 // March 13, 2011 02:15 never occurred, while November 6, 2011 01:15 00899 // occurred twice---so requests for such times are not well-defined. 00900 // To account for these possibilities, `absl::TimeZone::TimeInfo` is 00901 // richer than just a single `absl::Time`. 00902 struct TimeInfo { 00903 enum CivilKind { 00904 UNIQUE, // the civil time was singular (pre == trans == post) 00905 SKIPPED, // the civil time did not exist (pre >= trans > post) 00906 REPEATED, // the civil time was ambiguous (pre < trans <= post) 00907 } kind; 00908 Time pre; // time calculated using the pre-transition offset 00909 Time trans; // when the civil-time discontinuity occurred 00910 Time post; // time calculated using the post-transition offset 00911 }; 00912 00913 // TimeZone::At(CivilSecond) 00914 // 00915 // Returns an `absl::TimeInfo` containing the absolute time(s) for this 00916 // TimeZone at an `absl::CivilSecond`. When the civil time is skipped or 00917 // repeated, returns times calculated using the pre-transition and post- 00918 // transition UTC offsets, plus the transition time itself. 00919 // 00920 // Examples: 00921 // 00922 // // A unique civil time 00923 // const auto jan01 = lax.At(absl::CivilSecond(2011, 1, 1, 0, 0, 0)); 00924 // // jan01.kind == TimeZone::TimeInfo::UNIQUE 00925 // // jan01.pre is 2011-01-01 00:00:00 -0800 00926 // // jan01.trans is 2011-01-01 00:00:00 -0800 00927 // // jan01.post is 2011-01-01 00:00:00 -0800 00928 // 00929 // // A Spring DST transition, when there is a gap in civil time 00930 // const auto mar13 = lax.At(absl::CivilSecond(2011, 3, 13, 2, 15, 0)); 00931 // // mar13.kind == TimeZone::TimeInfo::SKIPPED 00932 // // mar13.pre is 2011-03-13 03:15:00 -0700 00933 // // mar13.trans is 2011-03-13 03:00:00 -0700 00934 // // mar13.post is 2011-03-13 01:15:00 -0800 00935 // 00936 // // A Fall DST transition, when civil times are repeated 00937 // const auto nov06 = lax.At(absl::CivilSecond(2011, 11, 6, 1, 15, 0)); 00938 // // nov06.kind == TimeZone::TimeInfo::REPEATED 00939 // // nov06.pre is 2011-11-06 01:15:00 -0700 00940 // // nov06.trans is 2011-11-06 01:00:00 -0800 00941 // // nov06.post is 2011-11-06 01:15:00 -0800 00942 TimeInfo At(CivilSecond ct) const; 00943 00944 // TimeZone::NextTransition() 00945 // TimeZone::PrevTransition() 00946 // 00947 // Finds the time of the next/previous offset change in this time zone. 00948 // 00949 // By definition, `NextTransition(t, &trans)` returns false when `t` is 00950 // `InfiniteFuture()`, and `PrevTransition(t, &trans)` returns false 00951 // when `t` is `InfinitePast()`. If the zone has no transitions, the 00952 // result will also be false no matter what the argument. 00953 // 00954 // Otherwise, when `t` is `InfinitePast()`, `NextTransition(t, &trans)` 00955 // returns true and sets `trans` to the first recorded transition. Chains 00956 // of calls to `NextTransition()/PrevTransition()` will eventually return 00957 // false, but it is unspecified exactly when `NextTransition(t, &trans)` 00958 // jumps to false, or what time is set by `PrevTransition(t, &trans)` for 00959 // a very distant `t`. 00960 // 00961 // Note: Enumeration of time-zone transitions is for informational purposes 00962 // only. Modern time-related code should not care about when offset changes 00963 // occur. 00964 // 00965 // Example: 00966 // absl::TimeZone nyc; 00967 // if (!absl::LoadTimeZone("America/New_York", &nyc)) { ... } 00968 // const auto now = absl::Now(); 00969 // auto t = absl::InfinitePast(); 00970 // absl::TimeZone::CivilTransition trans; 00971 // while (t <= now && nyc.NextTransition(t, &trans)) { 00972 // // transition: trans.from -> trans.to 00973 // t = nyc.At(trans.to).trans; 00974 // } 00975 struct CivilTransition { 00976 CivilSecond from; // the civil time we jump from 00977 CivilSecond to; // the civil time we jump to 00978 }; 00979 bool NextTransition(Time t, CivilTransition* trans) const; 00980 bool PrevTransition(Time t, CivilTransition* trans) const; 00981 00982 template <typename H> 00983 friend H AbslHashValue(H h, TimeZone tz) { 00984 return H::combine(std::move(h), tz.cz_); 00985 } 00986 00987 private: 00988 friend bool operator==(TimeZone a, TimeZone b) { return a.cz_ == b.cz_; } 00989 friend bool operator!=(TimeZone a, TimeZone b) { return a.cz_ != b.cz_; } 00990 friend std::ostream& operator<<(std::ostream& os, TimeZone tz) { 00991 return os << tz.name(); 00992 } 00993 00994 time_internal::cctz::time_zone cz_; 00995 }; 00996 00997 // LoadTimeZone() 00998 // 00999 // Loads the named zone. May perform I/O on the initial load of the named 01000 // zone. If the name is invalid, or some other kind of error occurs, returns 01001 // `false` and `*tz` is set to the UTC time zone. 01002 inline bool LoadTimeZone(const std::string& name, TimeZone* tz) { 01003 if (name == "localtime") { 01004 *tz = TimeZone(time_internal::cctz::local_time_zone()); 01005 return true; 01006 } 01007 time_internal::cctz::time_zone cz; 01008 const bool b = time_internal::cctz::load_time_zone(name, &cz); 01009 *tz = TimeZone(cz); 01010 return b; 01011 } 01012 01013 // FixedTimeZone() 01014 // 01015 // Returns a TimeZone that is a fixed offset (seconds east) from UTC. 01016 // Note: If the absolute value of the offset is greater than 24 hours 01017 // you'll get UTC (i.e., no offset) instead. 01018 inline TimeZone FixedTimeZone(int seconds) { 01019 return TimeZone( 01020 time_internal::cctz::fixed_time_zone(std::chrono::seconds(seconds))); 01021 } 01022 01023 // UTCTimeZone() 01024 // 01025 // Convenience method returning the UTC time zone. 01026 inline TimeZone UTCTimeZone() { 01027 return TimeZone(time_internal::cctz::utc_time_zone()); 01028 } 01029 01030 // LocalTimeZone() 01031 // 01032 // Convenience method returning the local time zone, or UTC if there is 01033 // no configured local zone. Warning: Be wary of using LocalTimeZone(), 01034 // and particularly so in a server process, as the zone configured for the 01035 // local machine should be irrelevant. Prefer an explicit zone name. 01036 inline TimeZone LocalTimeZone() { 01037 return TimeZone(time_internal::cctz::local_time_zone()); 01038 } 01039 01040 // ToCivilSecond() 01041 // ToCivilMinute() 01042 // ToCivilHour() 01043 // ToCivilDay() 01044 // ToCivilMonth() 01045 // ToCivilYear() 01046 // 01047 // Helpers for TimeZone::At(Time) to return particularly aligned civil times. 01048 // 01049 // Example: 01050 // 01051 // absl::Time t = ...; 01052 // absl::TimeZone tz = ...; 01053 // const auto cd = absl::ToCivilDay(t, tz); 01054 inline CivilSecond ToCivilSecond(Time t, TimeZone tz) { 01055 return tz.At(t).cs; // already a CivilSecond 01056 } 01057 inline CivilMinute ToCivilMinute(Time t, TimeZone tz) { 01058 return CivilMinute(tz.At(t).cs); 01059 } 01060 inline CivilHour ToCivilHour(Time t, TimeZone tz) { 01061 return CivilHour(tz.At(t).cs); 01062 } 01063 inline CivilDay ToCivilDay(Time t, TimeZone tz) { 01064 return CivilDay(tz.At(t).cs); 01065 } 01066 inline CivilMonth ToCivilMonth(Time t, TimeZone tz) { 01067 return CivilMonth(tz.At(t).cs); 01068 } 01069 inline CivilYear ToCivilYear(Time t, TimeZone tz) { 01070 return CivilYear(tz.At(t).cs); 01071 } 01072 01073 // FromCivil() 01074 // 01075 // Helper for TimeZone::At(CivilSecond) that provides "order-preserving 01076 // semantics." If the civil time maps to a unique time, that time is 01077 // returned. If the civil time is repeated in the given time zone, the 01078 // time using the pre-transition offset is returned. Otherwise, the 01079 // civil time is skipped in the given time zone, and the transition time 01080 // is returned. This means that for any two civil times, ct1 and ct2, 01081 // (ct1 < ct2) => (FromCivil(ct1) <= FromCivil(ct2)), the equal case 01082 // being when two non-existent civil times map to the same transition time. 01083 // 01084 // Note: Accepts civil times of any alignment. 01085 inline Time FromCivil(CivilSecond ct, TimeZone tz) { 01086 const auto ti = tz.At(ct); 01087 if (ti.kind == TimeZone::TimeInfo::SKIPPED) return ti.trans; 01088 return ti.pre; 01089 } 01090 01091 // TimeConversion 01092 // 01093 // An `absl::TimeConversion` represents the conversion of year, month, day, 01094 // hour, minute, and second values (i.e., a civil time), in a particular 01095 // `absl::TimeZone`, to a time instant (an absolute time), as returned by 01096 // `absl::ConvertDateTime()`. Lecacy version of `absl::TimeZone::TimeInfo`. 01097 // 01098 // Deprecated. Use `absl::TimeZone::TimeInfo`. 01099 struct 01100 TimeConversion { 01101 Time pre; // time calculated using the pre-transition offset 01102 Time trans; // when the civil-time discontinuity occurred 01103 Time post; // time calculated using the post-transition offset 01104 01105 enum Kind { 01106 UNIQUE, // the civil time was singular (pre == trans == post) 01107 SKIPPED, // the civil time did not exist 01108 REPEATED, // the civil time was ambiguous 01109 }; 01110 Kind kind; 01111 01112 bool normalized; // input values were outside their valid ranges 01113 }; 01114 01115 // ConvertDateTime() 01116 // 01117 // Legacy version of `absl::TimeZone::At(absl::CivilSecond)` that takes 01118 // the civil time as six, separate values (YMDHMS). 01119 // 01120 // The input month, day, hour, minute, and second values can be outside 01121 // of their valid ranges, in which case they will be "normalized" during 01122 // the conversion. 01123 // 01124 // Example: 01125 // 01126 // // "October 32" normalizes to "November 1". 01127 // absl::TimeConversion tc = 01128 // absl::ConvertDateTime(2013, 10, 32, 8, 30, 0, lax); 01129 // // tc.kind == TimeConversion::UNIQUE && tc.normalized == true 01130 // // absl::ToCivilDay(tc.pre, tz).month() == 11 01131 // // absl::ToCivilDay(tc.pre, tz).day() == 1 01132 // 01133 // Deprecated. Use `absl::TimeZone::At(CivilSecond)`. 01134 TimeConversion ConvertDateTime(int64_t year, int mon, int day, int hour, 01135 int min, int sec, TimeZone tz); 01136 01137 // FromDateTime() 01138 // 01139 // A convenience wrapper for `absl::ConvertDateTime()` that simply returns 01140 // the "pre" `absl::Time`. That is, the unique result, or the instant that 01141 // is correct using the pre-transition offset (as if the transition never 01142 // happened). 01143 // 01144 // Example: 01145 // 01146 // absl::Time t = absl::FromDateTime(2017, 9, 26, 9, 30, 0, lax); 01147 // // t = 2017-09-26 09:30:00 -0700 01148 // 01149 // Deprecated. Use `absl::FromCivil(CivilSecond, TimeZone)`. Note that the 01150 // behavior of `FromCivil()` differs from `FromDateTime()` for skipped civil 01151 // times. If you care about that see `absl::TimeZone::At(absl::CivilSecond)`. 01152 inline Time FromDateTime(int64_t year, int mon, int day, int hour, 01153 int min, int sec, TimeZone tz) { 01154 return ConvertDateTime(year, mon, day, hour, min, sec, tz).pre; 01155 } 01156 01157 // FromTM() 01158 // 01159 // Converts the `tm_year`, `tm_mon`, `tm_mday`, `tm_hour`, `tm_min`, and 01160 // `tm_sec` fields to an `absl::Time` using the given time zone. See ctime(3) 01161 // for a description of the expected values of the tm fields. If the indicated 01162 // time instant is not unique (see `absl::TimeZone::At(absl::CivilSecond)` 01163 // above), the `tm_isdst` field is consulted to select the desired instant 01164 // (`tm_isdst` > 0 means DST, `tm_isdst` == 0 means no DST, `tm_isdst` < 0 01165 // means use the post-transition offset). 01166 Time FromTM(const struct tm& tm, TimeZone tz); 01167 01168 // ToTM() 01169 // 01170 // Converts the given `absl::Time` to a struct tm using the given time zone. 01171 // See ctime(3) for a description of the values of the tm fields. 01172 struct tm ToTM(Time t, TimeZone tz); 01173 01174 // RFC3339_full 01175 // RFC3339_sec 01176 // 01177 // FormatTime()/ParseTime() format specifiers for RFC3339 date/time strings, 01178 // with trailing zeros trimmed or with fractional seconds omitted altogether. 01179 // 01180 // Note that RFC3339_sec[] matches an ISO 8601 extended format for date and 01181 // time with UTC offset. Also note the use of "%Y": RFC3339 mandates that 01182 // years have exactly four digits, but we allow them to take their natural 01183 // width. 01184 extern const char RFC3339_full[]; // %Y-%m-%dT%H:%M:%E*S%Ez 01185 extern const char RFC3339_sec[]; // %Y-%m-%dT%H:%M:%S%Ez 01186 01187 // RFC1123_full 01188 // RFC1123_no_wday 01189 // 01190 // FormatTime()/ParseTime() format specifiers for RFC1123 date/time strings. 01191 extern const char RFC1123_full[]; // %a, %d %b %E4Y %H:%M:%S %z 01192 extern const char RFC1123_no_wday[]; // %d %b %E4Y %H:%M:%S %z 01193 01194 // FormatTime() 01195 // 01196 // Formats the given `absl::Time` in the `absl::TimeZone` according to the 01197 // provided format string. Uses strftime()-like formatting options, with 01198 // the following extensions: 01199 // 01200 // - %Ez - RFC3339-compatible numeric UTC offset (+hh:mm or -hh:mm) 01201 // - %E*z - Full-resolution numeric UTC offset (+hh:mm:ss or -hh:mm:ss) 01202 // - %E#S - Seconds with # digits of fractional precision 01203 // - %E*S - Seconds with full fractional precision (a literal '*') 01204 // - %E#f - Fractional seconds with # digits of precision 01205 // - %E*f - Fractional seconds with full precision (a literal '*') 01206 // - %E4Y - Four-character years (-999 ... -001, 0000, 0001 ... 9999) 01207 // 01208 // Note that %E0S behaves like %S, and %E0f produces no characters. In 01209 // contrast %E*f always produces at least one digit, which may be '0'. 01210 // 01211 // Note that %Y produces as many characters as it takes to fully render the 01212 // year. A year outside of [-999:9999] when formatted with %E4Y will produce 01213 // more than four characters, just like %Y. 01214 // 01215 // We recommend that format strings include the UTC offset (%z, %Ez, or %E*z) 01216 // so that the result uniquely identifies a time instant. 01217 // 01218 // Example: 01219 // 01220 // absl::CivilSecond cs(2013, 1, 2, 3, 4, 5); 01221 // absl::Time t = absl::FromCivil(cs, lax); 01222 // std::string f = absl::FormatTime("%H:%M:%S", t, lax); // "03:04:05" 01223 // f = absl::FormatTime("%H:%M:%E3S", t, lax); // "03:04:05.000" 01224 // 01225 // Note: If the given `absl::Time` is `absl::InfiniteFuture()`, the returned 01226 // string will be exactly "infinite-future". If the given `absl::Time` is 01227 // `absl::InfinitePast()`, the returned string will be exactly "infinite-past". 01228 // In both cases the given format string and `absl::TimeZone` are ignored. 01229 // 01230 std::string FormatTime(const std::string& format, Time t, TimeZone tz); 01231 01232 // Convenience functions that format the given time using the RFC3339_full 01233 // format. The first overload uses the provided TimeZone, while the second 01234 // uses LocalTimeZone(). 01235 std::string FormatTime(Time t, TimeZone tz); 01236 std::string FormatTime(Time t); 01237 01238 // Output stream operator. 01239 inline std::ostream& operator<<(std::ostream& os, Time t) { 01240 return os << FormatTime(t); 01241 } 01242 01243 // ParseTime() 01244 // 01245 // Parses an input string according to the provided format string and 01246 // returns the corresponding `absl::Time`. Uses strftime()-like formatting 01247 // options, with the same extensions as FormatTime(), but with the 01248 // exceptions that %E#S is interpreted as %E*S, and %E#f as %E*f. %Ez 01249 // and %E*z also accept the same inputs. 01250 // 01251 // %Y consumes as many numeric characters as it can, so the matching data 01252 // should always be terminated with a non-numeric. %E4Y always consumes 01253 // exactly four characters, including any sign. 01254 // 01255 // Unspecified fields are taken from the default date and time of ... 01256 // 01257 // "1970-01-01 00:00:00.0 +0000" 01258 // 01259 // For example, parsing a string of "15:45" (%H:%M) will return an absl::Time 01260 // that represents "1970-01-01 15:45:00.0 +0000". 01261 // 01262 // Note that since ParseTime() returns time instants, it makes the most sense 01263 // to parse fully-specified date/time strings that include a UTC offset (%z, 01264 // %Ez, or %E*z). 01265 // 01266 // Note also that `absl::ParseTime()` only heeds the fields year, month, day, 01267 // hour, minute, (fractional) second, and UTC offset. Other fields, like 01268 // weekday (%a or %A), while parsed for syntactic validity, are ignored 01269 // in the conversion. 01270 // 01271 // Date and time fields that are out-of-range will be treated as errors 01272 // rather than normalizing them like `absl::CivilSecond` does. For example, 01273 // it is an error to parse the date "Oct 32, 2013" because 32 is out of range. 01274 // 01275 // A leap second of ":60" is normalized to ":00" of the following minute 01276 // with fractional seconds discarded. The following table shows how the 01277 // given seconds and subseconds will be parsed: 01278 // 01279 // "59.x" -> 59.x // exact 01280 // "60.x" -> 00.0 // normalized 01281 // "00.x" -> 00.x // exact 01282 // 01283 // Errors are indicated by returning false and assigning an error message 01284 // to the "err" out param if it is non-null. 01285 // 01286 // Note: If the input string is exactly "infinite-future", the returned 01287 // `absl::Time` will be `absl::InfiniteFuture()` and `true` will be returned. 01288 // If the input string is "infinite-past", the returned `absl::Time` will be 01289 // `absl::InfinitePast()` and `true` will be returned. 01290 // 01291 bool ParseTime(const std::string& format, const std::string& input, Time* time, 01292 std::string* err); 01293 01294 // Like ParseTime() above, but if the format string does not contain a UTC 01295 // offset specification (%z/%Ez/%E*z) then the input is interpreted in the 01296 // given TimeZone. This means that the input, by itself, does not identify a 01297 // unique instant. Being time-zone dependent, it also admits the possibility 01298 // of ambiguity or non-existence, in which case the "pre" time (as defined 01299 // by TimeZone::TimeInfo) is returned. For these reasons we recommend that 01300 // all date/time strings include a UTC offset so they're context independent. 01301 bool ParseTime(const std::string& format, const std::string& input, TimeZone tz, 01302 Time* time, std::string* err); 01303 01304 // ============================================================================ 01305 // Implementation Details Follow 01306 // ============================================================================ 01307 01308 namespace time_internal { 01309 01310 // Creates a Duration with a given representation. 01311 // REQUIRES: hi,lo is a valid representation of a Duration as specified 01312 // in time/duration.cc. 01313 constexpr Duration MakeDuration(int64_t hi, uint32_t lo = 0) { 01314 return Duration(hi, lo); 01315 } 01316 01317 constexpr Duration MakeDuration(int64_t hi, int64_t lo) { 01318 return MakeDuration(hi, static_cast<uint32_t>(lo)); 01319 } 01320 01321 // Make a Duration value from a floating-point number, as long as that number 01322 // is in the range [ 0 .. numeric_limits<int64_t>::max ), that is, as long as 01323 // it's positive and can be converted to int64_t without risk of UB. 01324 inline Duration MakePosDoubleDuration(double n) { 01325 const int64_t int_secs = static_cast<int64_t>(n); 01326 const uint32_t ticks = 01327 static_cast<uint32_t>((n - int_secs) * kTicksPerSecond + 0.5); 01328 return ticks < kTicksPerSecond 01329 ? MakeDuration(int_secs, ticks) 01330 : MakeDuration(int_secs + 1, ticks - kTicksPerSecond); 01331 } 01332 01333 // Creates a normalized Duration from an almost-normalized (sec,ticks) 01334 // pair. sec may be positive or negative. ticks must be in the range 01335 // -kTicksPerSecond < *ticks < kTicksPerSecond. If ticks is negative it 01336 // will be normalized to a positive value in the resulting Duration. 01337 constexpr Duration MakeNormalizedDuration(int64_t sec, int64_t ticks) { 01338 return (ticks < 0) ? MakeDuration(sec - 1, ticks + kTicksPerSecond) 01339 : MakeDuration(sec, ticks); 01340 } 01341 01342 // Provide access to the Duration representation. 01343 constexpr int64_t GetRepHi(Duration d) { return d.rep_hi_; } 01344 constexpr uint32_t GetRepLo(Duration d) { return d.rep_lo_; } 01345 01346 // Returns true iff d is positive or negative infinity. 01347 constexpr bool IsInfiniteDuration(Duration d) { return GetRepLo(d) == ~0U; } 01348 01349 // Returns an infinite Duration with the opposite sign. 01350 // REQUIRES: IsInfiniteDuration(d) 01351 constexpr Duration OppositeInfinity(Duration d) { 01352 return GetRepHi(d) < 0 01353 ? MakeDuration((std::numeric_limits<int64_t>::max)(), ~0U) 01354 : MakeDuration((std::numeric_limits<int64_t>::min)(), ~0U); 01355 } 01356 01357 // Returns (-n)-1 (equivalently -(n+1)) without avoidable overflow. 01358 constexpr int64_t NegateAndSubtractOne(int64_t n) { 01359 // Note: Good compilers will optimize this expression to ~n when using 01360 // a two's-complement representation (which is required for int64_t). 01361 return (n < 0) ? -(n + 1) : (-n) - 1; 01362 } 01363 01364 // Map between a Time and a Duration since the Unix epoch. Note that these 01365 // functions depend on the above mentioned choice of the Unix epoch for the 01366 // Time representation (and both need to be Time friends). Without this 01367 // knowledge, we would need to add-in/subtract-out UnixEpoch() respectively. 01368 constexpr Time FromUnixDuration(Duration d) { return Time(d); } 01369 constexpr Duration ToUnixDuration(Time t) { return t.rep_; } 01370 01371 template <std::intmax_t N> 01372 constexpr Duration FromInt64(int64_t v, std::ratio<1, N>) { 01373 static_assert(0 < N && N <= 1000 * 1000 * 1000, "Unsupported ratio"); 01374 // Subsecond ratios cannot overflow. 01375 return MakeNormalizedDuration( 01376 v / N, v % N * kTicksPerNanosecond * 1000 * 1000 * 1000 / N); 01377 } 01378 constexpr Duration FromInt64(int64_t v, std::ratio<60>) { 01379 return (v <= (std::numeric_limits<int64_t>::max)() / 60 && 01380 v >= (std::numeric_limits<int64_t>::min)() / 60) 01381 ? MakeDuration(v * 60) 01382 : v > 0 ? InfiniteDuration() : -InfiniteDuration(); 01383 } 01384 constexpr Duration FromInt64(int64_t v, std::ratio<3600>) { 01385 return (v <= (std::numeric_limits<int64_t>::max)() / 3600 && 01386 v >= (std::numeric_limits<int64_t>::min)() / 3600) 01387 ? MakeDuration(v * 3600) 01388 : v > 0 ? InfiniteDuration() : -InfiniteDuration(); 01389 } 01390 01391 // IsValidRep64<T>(0) is true if the expression `int64_t{std::declval<T>()}` is 01392 // valid. That is, if a T can be assigned to an int64_t without narrowing. 01393 template <typename T> 01394 constexpr auto IsValidRep64(int) 01395 -> decltype(int64_t{std::declval<T>()}, bool()) { 01396 return true; 01397 } 01398 template <typename T> 01399 constexpr auto IsValidRep64(char) -> bool { 01400 return false; 01401 } 01402 01403 // Converts a std::chrono::duration to an absl::Duration. 01404 template <typename Rep, typename Period> 01405 constexpr Duration FromChrono(const std::chrono::duration<Rep, Period>& d) { 01406 static_assert(IsValidRep64<Rep>(0), "duration::rep is invalid"); 01407 return FromInt64(int64_t{d.count()}, Period{}); 01408 } 01409 01410 template <typename Ratio> 01411 int64_t ToInt64(Duration d, Ratio) { 01412 // Note: This may be used on MSVC, which may have a system_clock period of 01413 // std::ratio<1, 10 * 1000 * 1000> 01414 return ToInt64Seconds(d * Ratio::den / Ratio::num); 01415 } 01416 // Fastpath implementations for the 6 common duration units. 01417 inline int64_t ToInt64(Duration d, std::nano) { 01418 return ToInt64Nanoseconds(d); 01419 } 01420 inline int64_t ToInt64(Duration d, std::micro) { 01421 return ToInt64Microseconds(d); 01422 } 01423 inline int64_t ToInt64(Duration d, std::milli) { 01424 return ToInt64Milliseconds(d); 01425 } 01426 inline int64_t ToInt64(Duration d, std::ratio<1>) { 01427 return ToInt64Seconds(d); 01428 } 01429 inline int64_t ToInt64(Duration d, std::ratio<60>) { 01430 return ToInt64Minutes(d); 01431 } 01432 inline int64_t ToInt64(Duration d, std::ratio<3600>) { 01433 return ToInt64Hours(d); 01434 } 01435 01436 // Converts an absl::Duration to a chrono duration of type T. 01437 template <typename T> 01438 T ToChronoDuration(Duration d) { 01439 using Rep = typename T::rep; 01440 using Period = typename T::period; 01441 static_assert(IsValidRep64<Rep>(0), "duration::rep is invalid"); 01442 if (time_internal::IsInfiniteDuration(d)) 01443 return d < ZeroDuration() ? (T::min)() : (T::max)(); 01444 const auto v = ToInt64(d, Period{}); 01445 if (v > (std::numeric_limits<Rep>::max)()) return (T::max)(); 01446 if (v < (std::numeric_limits<Rep>::min)()) return (T::min)(); 01447 return T{v}; 01448 } 01449 01450 } // namespace time_internal 01451 01452 constexpr Duration Nanoseconds(int64_t n) { 01453 return time_internal::FromInt64(n, std::nano{}); 01454 } 01455 constexpr Duration Microseconds(int64_t n) { 01456 return time_internal::FromInt64(n, std::micro{}); 01457 } 01458 constexpr Duration Milliseconds(int64_t n) { 01459 return time_internal::FromInt64(n, std::milli{}); 01460 } 01461 constexpr Duration Seconds(int64_t n) { 01462 return time_internal::FromInt64(n, std::ratio<1>{}); 01463 } 01464 constexpr Duration Minutes(int64_t n) { 01465 return time_internal::FromInt64(n, std::ratio<60>{}); 01466 } 01467 constexpr Duration Hours(int64_t n) { 01468 return time_internal::FromInt64(n, std::ratio<3600>{}); 01469 } 01470 01471 constexpr bool operator<(Duration lhs, Duration rhs) { 01472 return time_internal::GetRepHi(lhs) != time_internal::GetRepHi(rhs) 01473 ? time_internal::GetRepHi(lhs) < time_internal::GetRepHi(rhs) 01474 : time_internal::GetRepHi(lhs) == 01475 (std::numeric_limits<int64_t>::min)() 01476 ? time_internal::GetRepLo(lhs) + 1 < 01477 time_internal::GetRepLo(rhs) + 1 01478 : time_internal::GetRepLo(lhs) < 01479 time_internal::GetRepLo(rhs); 01480 } 01481 01482 constexpr bool operator==(Duration lhs, Duration rhs) { 01483 return time_internal::GetRepHi(lhs) == time_internal::GetRepHi(rhs) && 01484 time_internal::GetRepLo(lhs) == time_internal::GetRepLo(rhs); 01485 } 01486 01487 constexpr Duration operator-(Duration d) { 01488 // This is a little interesting because of the special cases. 01489 // 01490 // If rep_lo_ is zero, we have it easy; it's safe to negate rep_hi_, we're 01491 // dealing with an integral number of seconds, and the only special case is 01492 // the maximum negative finite duration, which can't be negated. 01493 // 01494 // Infinities stay infinite, and just change direction. 01495 // 01496 // Finally we're in the case where rep_lo_ is non-zero, and we can borrow 01497 // a second's worth of ticks and avoid overflow (as negating int64_t-min + 1 01498 // is safe). 01499 return time_internal::GetRepLo(d) == 0 01500 ? time_internal::GetRepHi(d) == 01501 (std::numeric_limits<int64_t>::min)() 01502 ? InfiniteDuration() 01503 : time_internal::MakeDuration(-time_internal::GetRepHi(d)) 01504 : time_internal::IsInfiniteDuration(d) 01505 ? time_internal::OppositeInfinity(d) 01506 : time_internal::MakeDuration( 01507 time_internal::NegateAndSubtractOne( 01508 time_internal::GetRepHi(d)), 01509 time_internal::kTicksPerSecond - 01510 time_internal::GetRepLo(d)); 01511 } 01512 01513 constexpr Duration InfiniteDuration() { 01514 return time_internal::MakeDuration((std::numeric_limits<int64_t>::max)(), 01515 ~0U); 01516 } 01517 01518 constexpr Duration FromChrono(const std::chrono::nanoseconds& d) { 01519 return time_internal::FromChrono(d); 01520 } 01521 constexpr Duration FromChrono(const std::chrono::microseconds& d) { 01522 return time_internal::FromChrono(d); 01523 } 01524 constexpr Duration FromChrono(const std::chrono::milliseconds& d) { 01525 return time_internal::FromChrono(d); 01526 } 01527 constexpr Duration FromChrono(const std::chrono::seconds& d) { 01528 return time_internal::FromChrono(d); 01529 } 01530 constexpr Duration FromChrono(const std::chrono::minutes& d) { 01531 return time_internal::FromChrono(d); 01532 } 01533 constexpr Duration FromChrono(const std::chrono::hours& d) { 01534 return time_internal::FromChrono(d); 01535 } 01536 01537 constexpr Time FromUnixNanos(int64_t ns) { 01538 return time_internal::FromUnixDuration(Nanoseconds(ns)); 01539 } 01540 01541 constexpr Time FromUnixMicros(int64_t us) { 01542 return time_internal::FromUnixDuration(Microseconds(us)); 01543 } 01544 01545 constexpr Time FromUnixMillis(int64_t ms) { 01546 return time_internal::FromUnixDuration(Milliseconds(ms)); 01547 } 01548 01549 constexpr Time FromUnixSeconds(int64_t s) { 01550 return time_internal::FromUnixDuration(Seconds(s)); 01551 } 01552 01553 constexpr Time FromTimeT(time_t t) { 01554 return time_internal::FromUnixDuration(Seconds(t)); 01555 } 01556 01557 } // namespace absl 01558 01559 #endif // ABSL_TIME_TIME_H_