time.h 70 KB

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