time.h 59 KB

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