time.h 71 KB

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