time.h 67 KB

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