times.nim 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2018 Nim contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ##[
  10. The `times` module contains routines and types for dealing with time using
  11. the `proleptic Gregorian calendar<https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar>`_.
  12. It's also available for the
  13. `JavaScript target <backends.html#backends-the-javascript-target>`_.
  14. Although the `times` module supports nanosecond time resolution, the
  15. resolution used by `getTime()` depends on the platform and backend
  16. (JS is limited to millisecond precision).
  17. Examples
  18. ========
  19. .. code-block:: nim
  20. import std/[times, os]
  21. # Simple benchmarking
  22. let time = cpuTime()
  23. sleep(100) # Replace this with something to be timed
  24. echo "Time taken: ", cpuTime() - time
  25. # Current date & time
  26. let now1 = now() # Current timestamp as a DateTime in local time
  27. let now2 = now().utc # Current timestamp as a DateTime in UTC
  28. let now3 = getTime() # Current timestamp as a Time
  29. # Arithmetic using Duration
  30. echo "One hour from now : ", now() + initDuration(hours = 1)
  31. # Arithmetic using TimeInterval
  32. echo "One year from now : ", now() + 1.years
  33. echo "One month from now : ", now() + 1.months
  34. Parsing and Formatting Dates
  35. ============================
  36. The `DateTime` type can be parsed and formatted using the different
  37. `parse` and `format` procedures.
  38. .. code-block:: nim
  39. let dt = parse("2000-01-01", "yyyy-MM-dd")
  40. echo dt.format("yyyy-MM-dd")
  41. The different format patterns that are supported are documented below.
  42. =========== ================================================================================= ==============================================
  43. Pattern Description Example
  44. =========== ================================================================================= ==============================================
  45. `d` Numeric value representing the day of the month, | `1/04/2012 -> 1`
  46. it will be either one or two digits long. | `21/04/2012 -> 21`
  47. `dd` Same as above, but is always two digits. | `1/04/2012 -> 01`
  48. | `21/04/2012 -> 21`
  49. `ddd` Three letter string which indicates the day of the week. | `Saturday -> Sat`
  50. | `Monday -> Mon`
  51. `dddd` Full string for the day of the week. | `Saturday -> Saturday`
  52. | `Monday -> Monday`
  53. `GG` The last two digits of the Iso Week-Year | `30/12/2012 -> 13`
  54. `GGGG` The Iso week-calendar year padded to four digits | `30/12/2012 -> 2013`
  55. `h` The hours in one digit if possible. Ranging from 1-12. | `5pm -> 5`
  56. | `2am -> 2`
  57. `hh` The hours in two digits always. If the hour is one digit, 0 is prepended. | `5pm -> 05`
  58. | `11am -> 11`
  59. `H` The hours in one digit if possible, ranging from 0-23. | `5pm -> 17`
  60. | `2am -> 2`
  61. `HH` The hours in two digits always. 0 is prepended if the hour is one digit. | `5pm -> 17`
  62. | `2am -> 02`
  63. `m` The minutes in one digit if possible. | `5:30 -> 30`
  64. | `2:01 -> 1`
  65. `mm` Same as above but always two digits, 0 is prepended if the minute is one digit. | `5:30 -> 30`
  66. | `2:01 -> 01`
  67. `M` The month in one digit if possible. | `September -> 9`
  68. | `December -> 12`
  69. `MM` The month in two digits always. 0 is prepended if the month value is one digit. | `September -> 09`
  70. | `December -> 12`
  71. `MMM` Abbreviated three-letter form of the month. | `September -> Sep`
  72. | `December -> Dec`
  73. `MMMM` Full month string, properly capitalized. | `September -> September`
  74. `s` Seconds as one digit if possible. | `00:00:06 -> 6`
  75. `ss` Same as above but always two digits. 0 is prepended if the second is one digit. | `00:00:06 -> 06`
  76. `t` `A` when time is in the AM. `P` when time is in the PM. | `5pm -> P`
  77. | `2am -> A`
  78. `tt` Same as above, but `AM` and `PM` instead of `A` and `P` respectively. | `5pm -> PM`
  79. | `2am -> AM`
  80. `yy` The last two digits of the year. When parsing, the current century is assumed. | `2012 AD -> 12`
  81. `yyyy` The year, padded to at least four digits. | `2012 AD -> 2012`
  82. Is always positive, even when the year is BC. | `24 AD -> 0024`
  83. When the year is more than four digits, '+' is prepended. | `24 BC -> 00024`
  84. | `12345 AD -> +12345`
  85. `YYYY` The year without any padding. | `2012 AD -> 2012`
  86. Is always positive, even when the year is BC. | `24 AD -> 24`
  87. | `24 BC -> 24`
  88. | `12345 AD -> 12345`
  89. `uuuu` The year, padded to at least four digits. Will be negative when the year is BC. | `2012 AD -> 2012`
  90. When the year is more than four digits, '+' is prepended unless the year is BC. | `24 AD -> 0024`
  91. | `24 BC -> -0023`
  92. | `12345 AD -> +12345`
  93. `UUUU` The year without any padding. Will be negative when the year is BC. | `2012 AD -> 2012`
  94. | `24 AD -> 24`
  95. | `24 BC -> -23`
  96. | `12345 AD -> 12345`
  97. `V` The Iso Week-Number as one or two digits | `3/2/2012 -> 5`
  98. | `1/4/2012 -> 13`
  99. `VV` The Iso Week-Number as two digits always. 0 is prepended if one digit. | `3/2/2012 -> 05`
  100. | `1/4/2012 -> 13`
  101. `z` Displays the timezone offset from UTC. | `UTC+7 -> +7`
  102. | `UTC-5 -> -5`
  103. `zz` Same as above but with leading 0. | `UTC+7 -> +07`
  104. | `UTC-5 -> -05`
  105. `zzz` Same as above but with `:mm` where *mm* represents minutes. | `UTC+7 -> +07:00`
  106. | `UTC-5 -> -05:00`
  107. `ZZZ` Same as above but with `mm` where *mm* represents minutes. | `UTC+7 -> +0700`
  108. | `UTC-5 -> -0500`
  109. `zzzz` Same as above but with `:ss` where *ss* represents seconds. | `UTC+7 -> +07:00:00`
  110. | `UTC-5 -> -05:00:00`
  111. `ZZZZ` Same as above but with `ss` where *ss* represents seconds. | `UTC+7 -> +070000`
  112. | `UTC-5 -> -050000`
  113. `g` Era: AD or BC | `300 AD -> AD`
  114. | `300 BC -> BC`
  115. `fff` Milliseconds display | `1000000 nanoseconds -> 1`
  116. `ffffff` Microseconds display | `1000000 nanoseconds -> 1000`
  117. `fffffffff` Nanoseconds display | `1000000 nanoseconds -> 1000000`
  118. =========== ================================================================================= ==============================================
  119. Other strings can be inserted by putting them in `''`. For example
  120. `hh'->'mm` will give `01->56`. The following characters can be
  121. inserted without quoting them: `:` `-` `(` `)` `/` `[` `]`
  122. `,`. A literal `'` can be specified with `''`.
  123. However you don't need to necessarily separate format patterns, as an
  124. unambiguous format string like `yyyyMMddhhmmss` is also valid (although
  125. only for years in the range 1..9999).
  126. Duration vs TimeInterval
  127. ============================
  128. The `times` module exports two similar types that are both used to
  129. represent some amount of time: `Duration <#Duration>`_ and
  130. `TimeInterval <#TimeInterval>`_.
  131. This section explains how they differ and when one should be preferred over the
  132. other (short answer: use `Duration` unless support for months and years is
  133. needed).
  134. Duration
  135. ----------------------------
  136. A `Duration` represents a duration of time stored as seconds and
  137. nanoseconds. A `Duration` is always fully normalized, so
  138. `initDuration(hours = 1)` and `initDuration(minutes = 60)` are equivalent.
  139. Arithmetic with a `Duration` is very fast, especially when used with the
  140. `Time` type, since it only involves basic arithmetic. Because `Duration`
  141. is more performant and easier to understand it should generally preferred.
  142. TimeInterval
  143. ----------------------------
  144. A `TimeInterval` represents an amount of time expressed in calendar
  145. units, for example "1 year and 2 days". Since some units cannot be
  146. normalized (the length of a year is different for leap years for example),
  147. the `TimeInterval` type uses separate fields for every unit. The
  148. `TimeInterval`'s returned from this module generally don't normalize
  149. **anything**, so even units that could be normalized (like seconds,
  150. milliseconds and so on) are left untouched.
  151. Arithmetic with a `TimeInterval` can be very slow, because it requires
  152. timezone information.
  153. Since it's slower and more complex, the `TimeInterval` type should be
  154. avoided unless the program explicitly needs the features it offers that
  155. `Duration` doesn't have.
  156. How long is a day?
  157. ----------------------------
  158. It should be especially noted that the handling of days differs between
  159. `TimeInterval` and `Duration`. The `Duration` type always treats a day
  160. as exactly 86400 seconds. For `TimeInterval`, it's more complex.
  161. As an example, consider the amount of time between these two timestamps, both
  162. in the same timezone:
  163. - 2018-03-25T12:00+02:00
  164. - 2018-03-26T12:00+01:00
  165. If only the date & time is considered, it appears that exactly one day has
  166. passed. However, the UTC offsets are different, which means that the
  167. UTC offset was changed somewhere in between. This happens twice each year for
  168. timezones that use daylight savings time. Because of this change, the amount
  169. of time that has passed is actually 25 hours.
  170. The `TimeInterval` type uses calendar units, and will say that exactly one
  171. day has passed. The `Duration` type on the other hand normalizes everything
  172. to seconds, and will therefore say that 90000 seconds has passed, which is
  173. the same as 25 hours.
  174. See also
  175. ========
  176. * `monotimes module <monotimes.html>`_
  177. ]##
  178. import strutils, math, options
  179. import std/private/since
  180. include "system/inclrtl"
  181. when defined(nimPreviewSlimSystem):
  182. import std/assertions
  183. when defined(js):
  184. import jscore
  185. # This is really bad, but overflow checks are broken badly for
  186. # ints on the JS backend. See #6752.
  187. {.push overflowChecks: off.}
  188. proc `*`(a, b: int64): int64 =
  189. system.`*`(a, b)
  190. proc `*`(a, b: int): int =
  191. system.`*`(a, b)
  192. proc `+`(a, b: int64): int64 =
  193. system.`+`(a, b)
  194. proc `+`(a, b: int): int =
  195. system.`+`(a, b)
  196. proc `-`(a, b: int64): int64 =
  197. system.`-`(a, b)
  198. proc `-`(a, b: int): int =
  199. system.`-`(a, b)
  200. proc inc(a: var int, b: int) =
  201. system.inc(a, b)
  202. proc inc(a: var int64, b: int) =
  203. system.inc(a, b)
  204. {.pop.}
  205. elif defined(posix):
  206. import posix
  207. type CTime = posix.Time
  208. when defined(macosx):
  209. proc gettimeofday(tp: var Timeval, unused: pointer = nil)
  210. {.importc: "gettimeofday", header: "<sys/time.h>", sideEffect.}
  211. elif defined(windows):
  212. import winlean, std/time_t
  213. type
  214. CTime = time_t.Time
  215. Tm {.importc: "struct tm", header: "<time.h>", final, pure.} = object
  216. tm_sec*: cint ## Seconds [0,60].
  217. tm_min*: cint ## Minutes [0,59].
  218. tm_hour*: cint ## Hour [0,23].
  219. tm_mday*: cint ## Day of month [1,31].
  220. tm_mon*: cint ## Month of year [0,11].
  221. tm_year*: cint ## Years since 1900.
  222. tm_wday*: cint ## Day of week [0,6] (Sunday =0).
  223. tm_yday*: cint ## Day of year [0,365].
  224. tm_isdst*: cint ## Daylight Savings flag.
  225. proc localtime(a1: var CTime): ptr Tm {.importc, header: "<time.h>", sideEffect.}
  226. type
  227. Month* = enum ## Represents a month. Note that the enum starts at `1`,
  228. ## so `ord(month)` will give the month number in the
  229. ## range `1..12`.
  230. mJan = (1, "January")
  231. mFeb = "February"
  232. mMar = "March"
  233. mApr = "April"
  234. mMay = "May"
  235. mJun = "June"
  236. mJul = "July"
  237. mAug = "August"
  238. mSep = "September"
  239. mOct = "October"
  240. mNov = "November"
  241. mDec = "December"
  242. WeekDay* = enum ## Represents a weekday.
  243. dMon = "Monday"
  244. dTue = "Tuesday"
  245. dWed = "Wednesday"
  246. dThu = "Thursday"
  247. dFri = "Friday"
  248. dSat = "Saturday"
  249. dSun = "Sunday"
  250. type
  251. MonthdayRange* = range[1..31]
  252. HourRange* = range[0..23]
  253. MinuteRange* = range[0..59]
  254. SecondRange* = range[0..60] ## \
  255. ## Includes the value 60 to allow for a leap second. Note however
  256. ## that the `second` of a `DateTime` will never be a leap second.
  257. YeardayRange* = range[0..365]
  258. NanosecondRange* = range[0..999_999_999]
  259. IsoWeekRange* = range[1 .. 53]
  260. ## An ISO 8601 calendar week number.
  261. IsoYear* = distinct int
  262. ## An ISO 8601 calendar year number.
  263. ##
  264. ## .. warning:: The ISO week-based year can correspond to the following or previous year from 29 December to January 3.
  265. Time* = object ## Represents a point in time.
  266. seconds: int64
  267. nanosecond: NanosecondRange
  268. DateTime* = object of RootObj ## \
  269. ## Represents a time in different parts. Although this type can represent
  270. ## leap seconds, they are generally not supported in this module. They are
  271. ## not ignored, but the `DateTime`'s returned by procedures in this
  272. ## module will never have a leap second.
  273. nanosecond: NanosecondRange
  274. second: SecondRange
  275. minute: MinuteRange
  276. hour: HourRange
  277. monthdayZero: int
  278. monthZero: int
  279. year: int
  280. weekday: WeekDay
  281. yearday: YeardayRange
  282. isDst: bool
  283. timezone: Timezone
  284. utcOffset: int
  285. Duration* = object ## Represents a fixed duration of time, meaning a duration
  286. ## that has constant length independent of the context.
  287. ##
  288. ## To create a new `Duration`, use `initDuration
  289. ## <#initDuration,int64,int64,int64,int64,int64,int64,int64,int64>`_.
  290. ## Instead of trying to access the private attributes, use
  291. ## `inSeconds <#inSeconds,Duration>`_ for converting to seconds and
  292. ## `inNanoseconds <#inNanoseconds,Duration>`_ for converting to nanoseconds.
  293. seconds: int64
  294. nanosecond: NanosecondRange
  295. TimeUnit* = enum ## Different units of time.
  296. Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes, Hours, Days,
  297. Weeks, Months, Years
  298. FixedTimeUnit* = range[Nanoseconds..Weeks] ## \
  299. ## Subrange of `TimeUnit` that only includes units of fixed duration.
  300. ## These are the units that can be represented by a `Duration`.
  301. TimeInterval* = object ## \
  302. ## Represents a non-fixed duration of time. Can be used to add and
  303. ## subtract non-fixed time units from a `DateTime <#DateTime>`_ or
  304. ## `Time <#Time>`_.
  305. ##
  306. ## Create a new `TimeInterval` with `initTimeInterval proc
  307. ## <#initTimeInterval,int,int,int,int,int,int,int,int,int,int>`_.
  308. ##
  309. ## Note that `TimeInterval` doesn't represent a fixed duration of time,
  310. ## since the duration of some units depend on the context (e.g a year
  311. ## can be either 365 or 366 days long). The non-fixed time units are
  312. ## years, months, days and week.
  313. ##
  314. ## Note that `TimeInterval`'s returned from the `times` module are
  315. ## never normalized. If you want to normalize a time unit,
  316. ## `Duration <#Duration>`_ should be used instead.
  317. nanoseconds*: int ## The number of nanoseconds
  318. microseconds*: int ## The number of microseconds
  319. milliseconds*: int ## The number of milliseconds
  320. seconds*: int ## The number of seconds
  321. minutes*: int ## The number of minutes
  322. hours*: int ## The number of hours
  323. days*: int ## The number of days
  324. weeks*: int ## The number of weeks
  325. months*: int ## The number of months
  326. years*: int ## The number of years
  327. Timezone* = ref object ## \
  328. ## Timezone interface for supporting `DateTime <#DateTime>`_\s of arbitrary
  329. ## timezones. The `times` module only supplies implementations for the
  330. ## system's local time and UTC.
  331. zonedTimeFromTimeImpl: proc (x: Time): ZonedTime
  332. {.tags: [], raises: [], benign.}
  333. zonedTimeFromAdjTimeImpl: proc (x: Time): ZonedTime
  334. {.tags: [], raises: [], benign.}
  335. name: string
  336. ZonedTime* = object ## Represents a point in time with an associated
  337. ## UTC offset and DST flag. This type is only used for
  338. ## implementing timezones.
  339. time*: Time ## The point in time being represented.
  340. utcOffset*: int ## The offset in seconds west of UTC,
  341. ## including any offset due to DST.
  342. isDst*: bool ## Determines whether DST is in effect.
  343. DurationParts* = array[FixedTimeUnit, int64] # Array of Duration parts starts
  344. TimeIntervalParts* = array[TimeUnit, int] # Array of Duration parts starts
  345. const
  346. secondsInMin = 60
  347. secondsInHour = 60*60
  348. secondsInDay = 60*60*24
  349. rateDiff = 10000000'i64 # 100 nsecs
  350. # The number of hectonanoseconds between 1601/01/01 (windows epoch)
  351. # and 1970/01/01 (unix epoch).
  352. epochDiff = 116444736000000000'i64
  353. const unitWeights: array[FixedTimeUnit, int64] = [
  354. 1'i64,
  355. 1000,
  356. 1_000_000,
  357. 1e9.int64,
  358. secondsInMin * 1e9.int64,
  359. secondsInHour * 1e9.int64,
  360. secondsInDay * 1e9.int64,
  361. 7 * secondsInDay * 1e9.int64,
  362. ]
  363. when (NimMajor, NimMinor) >= (1, 4):
  364. # Newer versions of Nim don't track defects
  365. {.pragma: parseFormatRaises, raises: [TimeParseError, TimeFormatParseError].}
  366. {.pragma: parseRaises, raises: [TimeParseError].}
  367. else:
  368. # Still track when using older versions
  369. {.pragma: parseFormatRaises, raises: [TimeParseError, TimeFormatParseError, Defect].}
  370. {.pragma: parseRaises, raises: [TimeParseError, Defect].}
  371. #
  372. # Helper procs
  373. #
  374. {.pragma: operator, rtl, noSideEffect, benign.}
  375. proc convert*[T: SomeInteger](unitFrom, unitTo: FixedTimeUnit, quantity: T): T
  376. {.inline.} =
  377. ## Convert a quantity of some duration unit to another duration unit.
  378. ## This proc only deals with integers, so the result might be truncated.
  379. runnableExamples:
  380. doAssert convert(Days, Hours, 2) == 48
  381. doAssert convert(Days, Weeks, 13) == 1 # Truncated
  382. doAssert convert(Seconds, Milliseconds, -1) == -1000
  383. if unitFrom < unitTo:
  384. (quantity div (unitWeights[unitTo] div unitWeights[unitFrom])).T
  385. else:
  386. ((unitWeights[unitFrom] div unitWeights[unitTo]) * quantity).T
  387. proc normalize[T: Duration|Time](seconds, nanoseconds: int64): T =
  388. ## Normalize a (seconds, nanoseconds) pair and return it as either
  389. ## a `Duration` or `Time`. A normalized `Duration|Time` has a
  390. ## positive nanosecond part in the range `NanosecondRange`.
  391. result.seconds = seconds + convert(Nanoseconds, Seconds, nanoseconds)
  392. var nanosecond = nanoseconds mod convert(Seconds, Nanoseconds, 1)
  393. if nanosecond < 0:
  394. nanosecond += convert(Seconds, Nanoseconds, 1)
  395. result.seconds -= 1
  396. result.nanosecond = nanosecond.int
  397. proc isLeapYear*(year: int): bool =
  398. ## Returns true if `year` is a leap year.
  399. runnableExamples:
  400. doAssert isLeapYear(2000)
  401. doAssert not isLeapYear(1900)
  402. year mod 4 == 0 and (year mod 100 != 0 or year mod 400 == 0)
  403. proc getDaysInMonth*(month: Month, year: int): int =
  404. ## Get the number of days in `month` of `year`.
  405. # http://www.dispersiondesign.com/articles/time/number_of_days_in_a_month
  406. runnableExamples:
  407. doAssert getDaysInMonth(mFeb, 2000) == 29
  408. doAssert getDaysInMonth(mFeb, 2001) == 28
  409. case month
  410. of mFeb: result = if isLeapYear(year): 29 else: 28
  411. of mApr, mJun, mSep, mNov: result = 30
  412. else: result = 31
  413. proc assertValidDate(monthday: MonthdayRange, month: Month, year: int)
  414. {.inline.} =
  415. assert monthday <= getDaysInMonth(month, year),
  416. $year & "-" & intToStr(ord(month), 2) & "-" & $monthday &
  417. " is not a valid date"
  418. proc toEpochDay(monthday: MonthdayRange, month: Month, year: int): int64 =
  419. ## Get the epoch day from a year/month/day date.
  420. ## The epoch day is the number of days since 1970/01/01
  421. ## (it might be negative).
  422. # Based on http://howardhinnant.github.io/date_algorithms.html
  423. assertValidDate monthday, month, year
  424. var (y, m, d) = (year, ord(month), monthday.int)
  425. if m <= 2:
  426. y.dec
  427. let era = (if y >= 0: y else: y-399) div 400
  428. let yoe = y - era * 400
  429. let doy = (153 * (m + (if m > 2: -3 else: 9)) + 2) div 5 + d-1
  430. let doe = yoe * 365 + yoe div 4 - yoe div 100 + doy
  431. return era * 146097 + doe - 719468
  432. proc fromEpochDay(epochday: int64):
  433. tuple[monthday: MonthdayRange, month: Month, year: int] =
  434. ## Get the year/month/day date from a epoch day.
  435. ## The epoch day is the number of days since 1970/01/01
  436. ## (it might be negative).
  437. # Based on http://howardhinnant.github.io/date_algorithms.html
  438. var z = epochday
  439. z.inc 719468
  440. let era = (if z >= 0: z else: z - 146096) div 146097
  441. let doe = z - era * 146097
  442. let yoe = (doe - doe div 1460 + doe div 36524 - doe div 146096) div 365
  443. let y = yoe + era * 400;
  444. let doy = doe - (365 * yoe + yoe div 4 - yoe div 100)
  445. let mp = (5 * doy + 2) div 153
  446. let d = doy - (153 * mp + 2) div 5 + 1
  447. let m = mp + (if mp < 10: 3 else: -9)
  448. return (d.MonthdayRange, m.Month, (y + ord(m <= 2)).int)
  449. proc getDayOfYear*(monthday: MonthdayRange, month: Month, year: int):
  450. YeardayRange {.tags: [], raises: [], benign.} =
  451. ## Returns the day of the year.
  452. ## Equivalent with `dateTime(year, month, monthday, 0, 0, 0, 0).yearday`.
  453. runnableExamples:
  454. doAssert getDayOfYear(1, mJan, 2000) == 0
  455. doAssert getDayOfYear(10, mJan, 2000) == 9
  456. doAssert getDayOfYear(10, mFeb, 2000) == 40
  457. assertValidDate monthday, month, year
  458. const daysUntilMonth: array[Month, int] =
  459. [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
  460. const daysUntilMonthLeap: array[Month, int] =
  461. [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]
  462. if isLeapYear(year):
  463. result = daysUntilMonthLeap[month] + monthday - 1
  464. else:
  465. result = daysUntilMonth[month] + monthday - 1
  466. proc getDayOfWeek*(monthday: MonthdayRange, month: Month, year: int): WeekDay
  467. {.tags: [], raises: [], benign.} =
  468. ## Returns the day of the week enum from day, month and year.
  469. ## Equivalent with `dateTime(year, month, monthday, 0, 0, 0, 0).weekday`.
  470. runnableExamples:
  471. doAssert getDayOfWeek(13, mJun, 1990) == dWed
  472. doAssert $getDayOfWeek(13, mJun, 1990) == "Wednesday"
  473. assertValidDate monthday, month, year
  474. # 1970-01-01 is a Thursday, we adjust to the previous Monday
  475. let days = toEpochDay(monthday, month, year) - 3
  476. let weeks = floorDiv(days, 7'i64)
  477. let wd = days - weeks * 7
  478. # The value of d is 0 for a Sunday, 1 for a Monday, 2 for a Tuesday, etc.
  479. # so we must correct for the WeekDay type.
  480. result = if wd == 0: dSun else: WeekDay(wd - 1)
  481. proc getDaysInYear*(year: int): int =
  482. ## Get the number of days in a `year`
  483. runnableExamples:
  484. doAssert getDaysInYear(2000) == 366
  485. doAssert getDaysInYear(2001) == 365
  486. result = 365 + (if isLeapYear(year): 1 else: 0)
  487. proc `==`*(a, b: IsoYear): bool {.borrow.}
  488. proc `$`*(p: IsoYear): string {.borrow.}
  489. proc getWeeksInIsoYear*(y: IsoYear): IsoWeekRange {.since: (1, 5).} =
  490. ## Returns the number of weeks in the specified ISO 8601 week-based year, which can be
  491. ## either 53 or 52.
  492. runnableExamples:
  493. assert getWeeksInIsoYear(IsoYear(2019)) == 52
  494. assert getWeeksInIsoYear(IsoYear(2020)) == 53
  495. var y = int(y)
  496. # support negative years
  497. y = if y < 0: 400 + y mod 400 else: y
  498. # source: https://webspace.science.uu.nl/~gent0113/calendar/isocalendar.htm
  499. let p = (y + (y div 4) - (y div 100) + (y div 400)) mod 7
  500. let y1 = y - 1
  501. let p1 = (y1 + (y1 div 4) - (y1 div 100) + (y1 div 400)) mod 7
  502. if p == 4 or p1 == 3: 53 else: 52
  503. proc getIsoWeekAndYear*(dt: DateTime):
  504. tuple[isoweek: IsoWeekRange, isoyear: IsoYear] {.since: (1, 5).} =
  505. ## Returns the ISO 8601 week and year.
  506. ##
  507. ## .. warning:: The ISO week-based year can correspond to the following or previous year from 29 December to January 3.
  508. runnableExamples:
  509. assert getIsoWeekAndYear(initDateTime(21, mApr, 2018, 00, 00, 00)) == (isoweek: 16.IsoWeekRange, isoyear: 2018.IsoYear)
  510. block:
  511. let (w, y) = getIsoWeekAndYear(initDateTime(30, mDec, 2019, 00, 00, 00))
  512. assert w == 01.IsoWeekRange
  513. assert y == 2020.IsoYear
  514. assert getIsoWeekAndYear(initDateTime(13, mSep, 2020, 00, 00, 00)) == (isoweek: 37.IsoWeekRange, isoyear: 2020.IsoYear)
  515. block:
  516. let (w, y) = getIsoWeekAndYear(initDateTime(2, mJan, 2021, 00, 00, 00))
  517. assert w.int > 52
  518. assert w.int < 54
  519. assert y.int mod 100 == 20
  520. # source: https://webspace.science.uu.nl/~gent0113/calendar/isocalendar.htm
  521. var w = (dt.yearday.int - dt.weekday.int + 10) div 7
  522. if w < 1:
  523. (isoweek: getWeeksInIsoYear(IsoYear(dt.year - 1)), isoyear: IsoYear(dt.year - 1))
  524. elif (w > getWeeksInIsoYear(IsoYear(dt.year))):
  525. (isoweek: IsoWeekRange(1), isoyear: IsoYear(dt.year + 1))
  526. else:
  527. (isoweek: IsoWeekRange(w), isoyear: IsoYear(dt.year))
  528. proc stringifyUnit(value: int | int64, unit: TimeUnit): string =
  529. ## Stringify time unit with it's name, lowercased
  530. let strUnit = $unit
  531. result = ""
  532. result.addInt value
  533. result.add ' '
  534. if abs(value) != 1:
  535. result.add(strUnit.toLowerAscii())
  536. else:
  537. result.add(strUnit[0..^2].toLowerAscii())
  538. proc humanizeParts(parts: seq[string]): string =
  539. ## Make date string parts human-readable
  540. result = ""
  541. if parts.len == 0:
  542. result.add "0 nanoseconds"
  543. elif parts.len == 1:
  544. result = parts[0]
  545. elif parts.len == 2:
  546. result = parts[0] & " and " & parts[1]
  547. else:
  548. for i in 0..high(parts)-1:
  549. result.add parts[i] & ", "
  550. result.add "and " & parts[high(parts)]
  551. template subImpl[T: Duration|Time](a: Duration|Time, b: Duration|Time): T =
  552. normalize[T](a.seconds - b.seconds, a.nanosecond - b.nanosecond)
  553. template addImpl[T: Duration|Time](a: Duration|Time, b: Duration|Time): T =
  554. normalize[T](a.seconds + b.seconds, a.nanosecond + b.nanosecond)
  555. template ltImpl(a: Duration|Time, b: Duration|Time): bool =
  556. a.seconds < b.seconds or (
  557. a.seconds == b.seconds and a.nanosecond < b.nanosecond)
  558. template lqImpl(a: Duration|Time, b: Duration|Time): bool =
  559. a.seconds < b.seconds or (
  560. a.seconds == b.seconds and a.nanosecond <= b.nanosecond)
  561. template eqImpl(a: Duration|Time, b: Duration|Time): bool =
  562. a.seconds == b.seconds and a.nanosecond == b.nanosecond
  563. #
  564. # Duration
  565. #
  566. const DurationZero* = Duration() ## \
  567. ## Zero value for durations. Useful for comparisons.
  568. ##
  569. ## .. code-block:: nim
  570. ##
  571. ## doAssert initDuration(seconds = 1) > DurationZero
  572. ## doAssert initDuration(seconds = 0) == DurationZero
  573. proc initDuration*(nanoseconds, microseconds, milliseconds,
  574. seconds, minutes, hours, days, weeks: int64 = 0): Duration =
  575. ## Create a new `Duration <#Duration>`_.
  576. runnableExamples:
  577. let dur = initDuration(seconds = 1, milliseconds = 1)
  578. doAssert dur.inMilliseconds == 1001
  579. doAssert dur.inSeconds == 1
  580. let seconds = convert(Weeks, Seconds, weeks) +
  581. convert(Days, Seconds, days) +
  582. convert(Minutes, Seconds, minutes) +
  583. convert(Hours, Seconds, hours) +
  584. convert(Seconds, Seconds, seconds) +
  585. convert(Milliseconds, Seconds, milliseconds) +
  586. convert(Microseconds, Seconds, microseconds) +
  587. convert(Nanoseconds, Seconds, nanoseconds)
  588. let nanoseconds = (convert(Milliseconds, Nanoseconds, milliseconds mod 1000) +
  589. convert(Microseconds, Nanoseconds, microseconds mod 1_000_000) +
  590. nanoseconds mod 1_000_000_000).int
  591. # Nanoseconds might be negative so we must normalize.
  592. result = normalize[Duration](seconds, nanoseconds)
  593. template convert(dur: Duration, unit: static[FixedTimeUnit]): int64 =
  594. # The correction is required due to how durations are normalized.
  595. # For example,` initDuration(nanoseconds = -1)` is stored as
  596. # { seconds = -1, nanoseconds = 999999999 }.
  597. when unit == Nanoseconds:
  598. dur.seconds * 1_000_000_000 + dur.nanosecond
  599. else:
  600. let correction = dur.seconds < 0 and dur.nanosecond > 0
  601. when unit >= Seconds:
  602. convert(Seconds, unit, dur.seconds + ord(correction))
  603. else:
  604. if correction:
  605. convert(Seconds, unit, dur.seconds + 1) -
  606. convert(Nanoseconds, unit,
  607. convert(Seconds, Nanoseconds, 1) - dur.nanosecond)
  608. else:
  609. convert(Seconds, unit, dur.seconds) +
  610. convert(Nanoseconds, unit, dur.nanosecond)
  611. proc inWeeks*(dur: Duration): int64 =
  612. ## Converts the duration to the number of whole weeks.
  613. runnableExamples:
  614. let dur = initDuration(days = 8)
  615. doAssert dur.inWeeks == 1
  616. dur.convert(Weeks)
  617. proc inDays*(dur: Duration): int64 =
  618. ## Converts the duration to the number of whole days.
  619. runnableExamples:
  620. let dur = initDuration(hours = -50)
  621. doAssert dur.inDays == -2
  622. dur.convert(Days)
  623. proc inHours*(dur: Duration): int64 =
  624. ## Converts the duration to the number of whole hours.
  625. runnableExamples:
  626. let dur = initDuration(minutes = 60, days = 2)
  627. doAssert dur.inHours == 49
  628. dur.convert(Hours)
  629. proc inMinutes*(dur: Duration): int64 =
  630. ## Converts the duration to the number of whole minutes.
  631. runnableExamples:
  632. let dur = initDuration(hours = 2, seconds = 10)
  633. doAssert dur.inMinutes == 120
  634. dur.convert(Minutes)
  635. proc inSeconds*(dur: Duration): int64 =
  636. ## Converts the duration to the number of whole seconds.
  637. runnableExamples:
  638. let dur = initDuration(hours = 2, milliseconds = 10)
  639. doAssert dur.inSeconds == 2 * 60 * 60
  640. dur.convert(Seconds)
  641. proc inMilliseconds*(dur: Duration): int64 =
  642. ## Converts the duration to the number of whole milliseconds.
  643. runnableExamples:
  644. let dur = initDuration(seconds = -2)
  645. doAssert dur.inMilliseconds == -2000
  646. dur.convert(Milliseconds)
  647. proc inMicroseconds*(dur: Duration): int64 =
  648. ## Converts the duration to the number of whole microseconds.
  649. runnableExamples:
  650. let dur = initDuration(seconds = -2)
  651. doAssert dur.inMicroseconds == -2000000
  652. dur.convert(Microseconds)
  653. proc inNanoseconds*(dur: Duration): int64 =
  654. ## Converts the duration to the number of whole nanoseconds.
  655. runnableExamples:
  656. let dur = initDuration(seconds = -2)
  657. doAssert dur.inNanoseconds == -2000000000
  658. dur.convert(Nanoseconds)
  659. proc toParts*(dur: Duration): DurationParts =
  660. ## Converts a duration into an array consisting of fixed time units.
  661. ##
  662. ## Each value in the array gives information about a specific unit of
  663. ## time, for example `result[Days]` gives a count of days.
  664. ##
  665. ## This procedure is useful for converting `Duration` values to strings.
  666. runnableExamples:
  667. var dp = toParts(initDuration(weeks = 2, days = 1))
  668. doAssert dp[Days] == 1
  669. doAssert dp[Weeks] == 2
  670. doAssert dp[Minutes] == 0
  671. dp = toParts(initDuration(days = -1))
  672. doAssert dp[Days] == -1
  673. var remS = dur.seconds
  674. var remNs = dur.nanosecond.int
  675. # Ensure the same sign for seconds and nanoseconds
  676. if remS < 0 and remNs != 0:
  677. remNs -= convert(Seconds, Nanoseconds, 1)
  678. remS.inc 1
  679. for unit in countdown(Weeks, Seconds):
  680. let quantity = convert(Seconds, unit, remS)
  681. remS = remS mod convert(unit, Seconds, 1)
  682. result[unit] = quantity
  683. for unit in countdown(Milliseconds, Nanoseconds):
  684. let quantity = convert(Nanoseconds, unit, remNs)
  685. remNs = remNs mod convert(unit, Nanoseconds, 1)
  686. result[unit] = quantity
  687. proc `$`*(dur: Duration): string =
  688. ## Human friendly string representation of a `Duration`.
  689. runnableExamples:
  690. doAssert $initDuration(seconds = 2) == "2 seconds"
  691. doAssert $initDuration(weeks = 1, days = 2) == "1 week and 2 days"
  692. doAssert $initDuration(hours = 1, minutes = 2, seconds = 3) ==
  693. "1 hour, 2 minutes, and 3 seconds"
  694. doAssert $initDuration(milliseconds = -1500) ==
  695. "-1 second and -500 milliseconds"
  696. var parts = newSeq[string]()
  697. var numParts = toParts(dur)
  698. for unit in countdown(Weeks, Nanoseconds):
  699. let quantity = numParts[unit]
  700. if quantity != 0.int64:
  701. parts.add(stringifyUnit(quantity, unit))
  702. result = humanizeParts(parts)
  703. proc `+`*(a, b: Duration): Duration {.operator, extern: "ntAddDuration".} =
  704. ## Add two durations together.
  705. runnableExamples:
  706. doAssert initDuration(seconds = 1) + initDuration(days = 1) ==
  707. initDuration(seconds = 1, days = 1)
  708. addImpl[Duration](a, b)
  709. proc `-`*(a, b: Duration): Duration {.operator, extern: "ntSubDuration".} =
  710. ## Subtract a duration from another.
  711. runnableExamples:
  712. doAssert initDuration(seconds = 1, days = 1) - initDuration(seconds = 1) ==
  713. initDuration(days = 1)
  714. subImpl[Duration](a, b)
  715. proc `-`*(a: Duration): Duration {.operator, extern: "ntReverseDuration".} =
  716. ## Reverse a duration.
  717. runnableExamples:
  718. doAssert -initDuration(seconds = 1) == initDuration(seconds = -1)
  719. normalize[Duration](-a.seconds, -a.nanosecond)
  720. proc `<`*(a, b: Duration): bool {.operator, extern: "ntLtDuration".} =
  721. ## Note that a duration can be negative,
  722. ## so even if `a < b` is true `a` might
  723. ## represent a larger absolute duration.
  724. ## Use `abs(a) < abs(b)` to compare the absolute
  725. ## duration.
  726. runnableExamples:
  727. doAssert initDuration(seconds = 1) < initDuration(seconds = 2)
  728. doAssert initDuration(seconds = -2) < initDuration(seconds = 1)
  729. doAssert initDuration(seconds = -2).abs < initDuration(seconds = 1).abs == false
  730. ltImpl(a, b)
  731. proc `<=`*(a, b: Duration): bool {.operator, extern: "ntLeDuration".} =
  732. lqImpl(a, b)
  733. proc `==`*(a, b: Duration): bool {.operator, extern: "ntEqDuration".} =
  734. runnableExamples:
  735. let
  736. d1 = initDuration(weeks = 1)
  737. d2 = initDuration(days = 7)
  738. doAssert d1 == d2
  739. eqImpl(a, b)
  740. proc `*`*(a: int64, b: Duration): Duration {.operator,
  741. extern: "ntMulInt64Duration".} =
  742. ## Multiply a duration by some scalar.
  743. runnableExamples:
  744. doAssert 5 * initDuration(seconds = 1) == initDuration(seconds = 5)
  745. doAssert 3 * initDuration(minutes = 45) == initDuration(hours = 2, minutes = 15)
  746. normalize[Duration](a * b.seconds, a * b.nanosecond)
  747. proc `*`*(a: Duration, b: int64): Duration {.operator,
  748. extern: "ntMulDuration".} =
  749. ## Multiply a duration by some scalar.
  750. runnableExamples:
  751. doAssert initDuration(seconds = 1) * 5 == initDuration(seconds = 5)
  752. doAssert initDuration(minutes = 45) * 3 == initDuration(hours = 2, minutes = 15)
  753. b * a
  754. proc `+=`*(d1: var Duration, d2: Duration) =
  755. d1 = d1 + d2
  756. proc `-=`*(dt: var Duration, ti: Duration) =
  757. dt = dt - ti
  758. proc `*=`*(a: var Duration, b: int) =
  759. a = a * b
  760. proc `div`*(a: Duration, b: int64): Duration {.operator,
  761. extern: "ntDivDuration".} =
  762. ## Integer division for durations.
  763. runnableExamples:
  764. doAssert initDuration(seconds = 3) div 2 ==
  765. initDuration(milliseconds = 1500)
  766. doAssert initDuration(minutes = 45) div 30 ==
  767. initDuration(minutes = 1, seconds = 30)
  768. doAssert initDuration(nanoseconds = 3) div 2 ==
  769. initDuration(nanoseconds = 1)
  770. let carryOver = convert(Seconds, Nanoseconds, a.seconds mod b)
  771. normalize[Duration](a.seconds div b, (a.nanosecond + carryOver) div b)
  772. proc high*(typ: typedesc[Duration]): Duration =
  773. ## Get the longest representable duration.
  774. initDuration(seconds = high(int64), nanoseconds = high(NanosecondRange))
  775. proc low*(typ: typedesc[Duration]): Duration =
  776. ## Get the longest representable duration of negative direction.
  777. initDuration(seconds = low(int64))
  778. proc abs*(a: Duration): Duration =
  779. runnableExamples:
  780. doAssert initDuration(milliseconds = -1500).abs ==
  781. initDuration(milliseconds = 1500)
  782. initDuration(seconds = abs(a.seconds), nanoseconds = -a.nanosecond)
  783. #
  784. # Time
  785. #
  786. proc initTime*(unix: int64, nanosecond: NanosecondRange): Time =
  787. ## Create a `Time <#Time>`_ from a unix timestamp and a nanosecond part.
  788. result.seconds = unix
  789. result.nanosecond = nanosecond
  790. proc nanosecond*(time: Time): NanosecondRange =
  791. ## Get the fractional part of a `Time` as the number
  792. ## of nanoseconds of the second.
  793. time.nanosecond
  794. proc fromUnix*(unix: int64): Time
  795. {.benign, tags: [], raises: [], noSideEffect.} =
  796. ## Convert a unix timestamp (seconds since `1970-01-01T00:00:00Z`)
  797. ## to a `Time`.
  798. runnableExamples:
  799. doAssert $fromUnix(0).utc == "1970-01-01T00:00:00Z"
  800. initTime(unix, 0)
  801. proc toUnix*(t: Time): int64 {.benign, tags: [], raises: [], noSideEffect.} =
  802. ## Convert `t` to a unix timestamp (seconds since `1970-01-01T00:00:00Z`).
  803. ## See also `toUnixFloat` for subsecond resolution.
  804. runnableExamples:
  805. doAssert fromUnix(0).toUnix() == 0
  806. t.seconds
  807. proc fromUnixFloat(seconds: float): Time {.benign, tags: [], raises: [], noSideEffect.} =
  808. ## Convert a unix timestamp in seconds to a `Time`; same as `fromUnix`
  809. ## but with subsecond resolution.
  810. runnableExamples:
  811. doAssert fromUnixFloat(123456.0) == fromUnixFloat(123456)
  812. doAssert fromUnixFloat(-123456.0) == fromUnixFloat(-123456)
  813. let secs = seconds.floor
  814. let nsecs = (seconds - secs) * 1e9
  815. initTime(secs.int64, nsecs.NanosecondRange)
  816. proc toUnixFloat(t: Time): float {.benign, tags: [], raises: [].} =
  817. ## Same as `toUnix` but using subsecond resolution.
  818. runnableExamples:
  819. let t = getTime()
  820. # `<` because of rounding errors
  821. doAssert abs(t.toUnixFloat().fromUnixFloat - t) < initDuration(nanoseconds = 1000)
  822. t.seconds.float + t.nanosecond / convert(Seconds, Nanoseconds, 1)
  823. since((1, 1)):
  824. export fromUnixFloat
  825. export toUnixFloat
  826. proc fromWinTime*(win: int64): Time =
  827. ## Convert a Windows file time (100-nanosecond intervals since
  828. ## `1601-01-01T00:00:00Z`) to a `Time`.
  829. const hnsecsPerSec = convert(Seconds, Nanoseconds, 1) div 100
  830. let nanos = floorMod(win, hnsecsPerSec) * 100
  831. let seconds = floorDiv(win - epochDiff, hnsecsPerSec)
  832. result = initTime(seconds, nanos)
  833. proc toWinTime*(t: Time): int64 =
  834. ## Convert `t` to a Windows file time (100-nanosecond intervals
  835. ## since `1601-01-01T00:00:00Z`).
  836. result = t.seconds * rateDiff + epochDiff + t.nanosecond div 100
  837. proc getTimeImpl(typ: typedesc[Time]): Time =
  838. discard "implemented in the vm"
  839. proc getTime*(): Time {.tags: [TimeEffect], benign.} =
  840. ## Gets the current time as a `Time` with up to nanosecond resolution.
  841. when nimvm:
  842. result = getTimeImpl(Time)
  843. else:
  844. when defined(js):
  845. let millis = newDate().getTime()
  846. let seconds = convert(Milliseconds, Seconds, millis)
  847. let nanos = convert(Milliseconds, Nanoseconds,
  848. millis mod convert(Seconds, Milliseconds, 1).int)
  849. result = initTime(seconds, nanos)
  850. elif defined(macosx):
  851. var a {.noinit.}: Timeval
  852. gettimeofday(a)
  853. result = initTime(a.tv_sec.int64,
  854. convert(Microseconds, Nanoseconds, a.tv_usec.int))
  855. elif defined(posix):
  856. var ts {.noinit.}: Timespec
  857. discard clock_gettime(CLOCK_REALTIME, ts)
  858. result = initTime(ts.tv_sec.int64, ts.tv_nsec.int)
  859. elif defined(windows):
  860. var f {.noinit.}: FILETIME
  861. getSystemTimeAsFileTime(f)
  862. result = fromWinTime(rdFileTime(f))
  863. proc `-`*(a, b: Time): Duration {.operator, extern: "ntDiffTime".} =
  864. ## Computes the duration between two points in time.
  865. runnableExamples:
  866. doAssert initTime(1000, 100) - initTime(500, 20) ==
  867. initDuration(minutes = 8, seconds = 20, nanoseconds = 80)
  868. subImpl[Duration](a, b)
  869. proc `+`*(a: Time, b: Duration): Time {.operator, extern: "ntAddTime".} =
  870. ## Add a duration of time to a `Time`.
  871. runnableExamples:
  872. doAssert (fromUnix(0) + initDuration(seconds = 1)) == fromUnix(1)
  873. addImpl[Time](a, b)
  874. proc `-`*(a: Time, b: Duration): Time {.operator, extern: "ntSubTime".} =
  875. ## Subtracts a duration of time from a `Time`.
  876. runnableExamples:
  877. doAssert (fromUnix(0) - initDuration(seconds = 1)) == fromUnix(-1)
  878. subImpl[Time](a, b)
  879. proc `<`*(a, b: Time): bool {.operator, extern: "ntLtTime".} =
  880. ## Returns true if `a < b`, that is if `a` happened before `b`.
  881. runnableExamples:
  882. doAssert initTime(50, 0) < initTime(99, 0)
  883. ltImpl(a, b)
  884. proc `<=`*(a, b: Time): bool {.operator, extern: "ntLeTime".} =
  885. ## Returns true if `a <= b`.
  886. lqImpl(a, b)
  887. proc `==`*(a, b: Time): bool {.operator, extern: "ntEqTime".} =
  888. ## Returns true if `a == b`, that is if both times represent the same point in time.
  889. eqImpl(a, b)
  890. proc `+=`*(t: var Time, b: Duration) =
  891. t = t + b
  892. proc `-=`*(t: var Time, b: Duration) =
  893. t = t - b
  894. proc high*(typ: typedesc[Time]): Time =
  895. initTime(high(int64), high(NanosecondRange))
  896. proc low*(typ: typedesc[Time]): Time =
  897. initTime(0, 0)
  898. #
  899. # DateTime & Timezone
  900. #
  901. template assertDateTimeInitialized(dt: DateTime) =
  902. assert dt.monthdayZero != 0, "Uninitialized datetime"
  903. proc nanosecond*(dt: DateTime): NanosecondRange {.inline.} =
  904. ## The number of nanoseconds after the second,
  905. ## in the range 0 to 999_999_999.
  906. assertDateTimeInitialized(dt)
  907. dt.nanosecond
  908. proc second*(dt: DateTime): SecondRange {.inline.} =
  909. ## The number of seconds after the minute,
  910. ## in the range 0 to 59.
  911. assertDateTimeInitialized(dt)
  912. dt.second
  913. proc minute*(dt: DateTime): MinuteRange {.inline.} =
  914. ## The number of minutes after the hour,
  915. ## in the range 0 to 59.
  916. assertDateTimeInitialized(dt)
  917. dt.minute
  918. proc hour*(dt: DateTime): HourRange {.inline.} =
  919. ## The number of hours past midnight,
  920. ## in the range 0 to 23.
  921. assertDateTimeInitialized(dt)
  922. dt.hour
  923. proc monthday*(dt: DateTime): MonthdayRange {.inline.} =
  924. ## The day of the month, in the range 1 to 31.
  925. assertDateTimeInitialized(dt)
  926. # 'cast' to avoid extra range check
  927. cast[MonthdayRange](dt.monthdayZero)
  928. proc month*(dt: DateTime): Month =
  929. ## The month as an enum, the ordinal value
  930. ## is in the range 1 to 12.
  931. assertDateTimeInitialized(dt)
  932. # 'cast' to avoid extra range check
  933. cast[Month](dt.monthZero)
  934. proc year*(dt: DateTime): int {.inline.} =
  935. ## The year, using astronomical year numbering
  936. ## (meaning that before year 1 is year 0,
  937. ## then year -1 and so on).
  938. assertDateTimeInitialized(dt)
  939. dt.year
  940. proc weekday*(dt: DateTime): WeekDay {.inline.} =
  941. ## The day of the week as an enum, the ordinal
  942. ## value is in the range 0 (monday) to 6 (sunday).
  943. assertDateTimeInitialized(dt)
  944. dt.weekday
  945. proc yearday*(dt: DateTime): YeardayRange {.inline.} =
  946. ## The number of days since January 1,
  947. ## in the range 0 to 365.
  948. assertDateTimeInitialized(dt)
  949. dt.yearday
  950. proc isDst*(dt: DateTime): bool {.inline.} =
  951. ## Determines whether DST is in effect.
  952. ## Always false for the JavaScript backend.
  953. assertDateTimeInitialized(dt)
  954. dt.isDst
  955. proc timezone*(dt: DateTime): Timezone {.inline.} =
  956. ## The timezone represented as an implementation
  957. ## of `Timezone`.
  958. assertDateTimeInitialized(dt)
  959. dt.timezone
  960. proc utcOffset*(dt: DateTime): int {.inline.} =
  961. ## The offset in seconds west of UTC, including
  962. ## any offset due to DST. Note that the sign of
  963. ## this number is the opposite of the one in a
  964. ## formatted offset string like `+01:00` (which
  965. ## would be equivalent to the UTC offset
  966. ## `-3600`).
  967. assertDateTimeInitialized(dt)
  968. dt.utcOffset
  969. proc isInitialized(dt: DateTime): bool =
  970. # Returns true if `dt` is not the (invalid) default value for `DateTime`.
  971. runnableExamples:
  972. doAssert now().isInitialized
  973. doAssert not default(DateTime).isInitialized
  974. dt.monthZero != 0
  975. since((1, 3)):
  976. export isInitialized
  977. proc isLeapDay*(dt: DateTime): bool {.since: (1, 1).} =
  978. ## Returns whether `t` is a leap day, i.e. Feb 29 in a leap year. This matters
  979. ## as it affects time offset calculations.
  980. runnableExamples:
  981. let dt = dateTime(2020, mFeb, 29, 00, 00, 00, 00, utc())
  982. doAssert dt.isLeapDay
  983. doAssert dt+1.years-1.years != dt
  984. let dt2 = dateTime(2020, mFeb, 28, 00, 00, 00, 00, utc())
  985. doAssert not dt2.isLeapDay
  986. doAssert dt2+1.years-1.years == dt2
  987. doAssertRaises(Exception): discard dateTime(2021, mFeb, 29, 00, 00, 00, 00, utc())
  988. assertDateTimeInitialized dt
  989. dt.year.isLeapYear and dt.month == mFeb and dt.monthday == 29
  990. proc toTime*(dt: DateTime): Time {.tags: [], raises: [], benign.} =
  991. ## Converts a `DateTime` to a `Time` representing the same point in time.
  992. assertDateTimeInitialized dt
  993. let epochDay = toEpochDay(dt.monthday, dt.month, dt.year)
  994. var seconds = epochDay * secondsInDay
  995. seconds.inc dt.hour * secondsInHour
  996. seconds.inc dt.minute * 60
  997. seconds.inc dt.second
  998. seconds.inc dt.utcOffset
  999. result = initTime(seconds, dt.nanosecond)
  1000. proc initDateTime(zt: ZonedTime, zone: Timezone): DateTime =
  1001. ## Create a new `DateTime` using `ZonedTime` in the specified timezone.
  1002. let adjTime = zt.time - initDuration(seconds = zt.utcOffset)
  1003. let s = adjTime.seconds
  1004. let epochday = floorDiv(s, secondsInDay)
  1005. var rem = s - epochday * secondsInDay
  1006. let hour = rem div secondsInHour
  1007. rem = rem - hour * secondsInHour
  1008. let minute = rem div secondsInMin
  1009. rem = rem - minute * secondsInMin
  1010. let second = rem
  1011. let (d, m, y) = fromEpochDay(epochday)
  1012. DateTime(
  1013. year: y,
  1014. monthZero: m.int,
  1015. monthdayZero: d,
  1016. hour: hour,
  1017. minute: minute,
  1018. second: second,
  1019. nanosecond: zt.time.nanosecond,
  1020. weekday: getDayOfWeek(d, m, y),
  1021. yearday: getDayOfYear(d, m, y),
  1022. isDst: zt.isDst,
  1023. timezone: zone,
  1024. utcOffset: zt.utcOffset
  1025. )
  1026. proc newTimezone*(
  1027. name: string,
  1028. zonedTimeFromTimeImpl: proc (time: Time): ZonedTime
  1029. {.tags: [], raises: [], benign.},
  1030. zonedTimeFromAdjTimeImpl: proc (adjTime: Time): ZonedTime
  1031. {.tags: [], raises: [], benign.}
  1032. ): owned Timezone =
  1033. ## Create a new `Timezone`.
  1034. ##
  1035. ## `zonedTimeFromTimeImpl` and `zonedTimeFromAdjTimeImpl` is used
  1036. ## as the underlying implementations for `zonedTimeFromTime` and
  1037. ## `zonedTimeFromAdjTime`.
  1038. ##
  1039. ## If possible, the name parameter should match the name used in the
  1040. ## tz database. If the timezone doesn't exist in the tz database, or if the
  1041. ## timezone name is unknown, then any string that describes the timezone
  1042. ## unambiguously can be used. Note that the timezones name is used for
  1043. ## checking equality!
  1044. runnableExamples:
  1045. proc utcTzInfo(time: Time): ZonedTime =
  1046. ZonedTime(utcOffset: 0, isDst: false, time: time)
  1047. let utc = newTimezone("Etc/UTC", utcTzInfo, utcTzInfo)
  1048. Timezone(
  1049. name: name,
  1050. zonedTimeFromTimeImpl: zonedTimeFromTimeImpl,
  1051. zonedTimeFromAdjTimeImpl: zonedTimeFromAdjTimeImpl
  1052. )
  1053. proc name*(zone: Timezone): string =
  1054. ## The name of the timezone.
  1055. ##
  1056. ## If possible, the name will be the name used in the tz database.
  1057. ## If the timezone doesn't exist in the tz database, or if the timezone
  1058. ## name is unknown, then any string that describes the timezone
  1059. ## unambiguously might be used. For example, the string "LOCAL" is used
  1060. ## for the system's local timezone.
  1061. ##
  1062. ## See also: https://en.wikipedia.org/wiki/Tz_database
  1063. zone.name
  1064. proc zonedTimeFromTime*(zone: Timezone, time: Time): ZonedTime =
  1065. ## Returns the `ZonedTime` for some point in time.
  1066. zone.zonedTimeFromTimeImpl(time)
  1067. proc zonedTimeFromAdjTime*(zone: Timezone, adjTime: Time): ZonedTime =
  1068. ## Returns the `ZonedTime` for some local time.
  1069. ##
  1070. ## Note that the `Time` argument does not represent a point in time, it
  1071. ## represent a local time! E.g if `adjTime` is `fromUnix(0)`, it should be
  1072. ## interpreted as 1970-01-01T00:00:00 in the `zone` timezone, not in UTC.
  1073. zone.zonedTimeFromAdjTimeImpl(adjTime)
  1074. proc `$`*(zone: Timezone): string =
  1075. ## Returns the name of the timezone.
  1076. if zone != nil: result = zone.name
  1077. proc `==`*(zone1, zone2: Timezone): bool =
  1078. ## Two `Timezone`'s are considered equal if their name is equal.
  1079. runnableExamples:
  1080. doAssert local() == local()
  1081. doAssert local() != utc()
  1082. if system.`==`(zone1, zone2):
  1083. return true
  1084. if zone1.isNil or zone2.isNil:
  1085. return false
  1086. zone1.name == zone2.name
  1087. proc inZone*(time: Time, zone: Timezone): DateTime
  1088. {.tags: [], raises: [], benign.} =
  1089. ## Convert `time` into a `DateTime` using `zone` as the timezone.
  1090. result = initDateTime(zone.zonedTimeFromTime(time), zone)
  1091. proc inZone*(dt: DateTime, zone: Timezone): DateTime
  1092. {.tags: [], raises: [], benign.} =
  1093. ## Returns a `DateTime` representing the same point in time as `dt` but
  1094. ## using `zone` as the timezone.
  1095. assertDateTimeInitialized dt
  1096. dt.toTime.inZone(zone)
  1097. proc toAdjTime(dt: DateTime): Time =
  1098. let epochDay = toEpochDay(dt.monthday, dt.month, dt.year)
  1099. var seconds = epochDay * secondsInDay
  1100. seconds.inc dt.hour * secondsInHour
  1101. seconds.inc dt.minute * secondsInMin
  1102. seconds.inc dt.second
  1103. result = initTime(seconds, dt.nanosecond)
  1104. when defined(js):
  1105. proc localZonedTimeFromTime(time: Time): ZonedTime {.benign.} =
  1106. let jsDate = newDate(time.seconds * 1000)
  1107. let offset = jsDate.getTimezoneOffset() * secondsInMin
  1108. result.time = time
  1109. result.utcOffset = offset
  1110. result.isDst = false
  1111. proc localZonedTimeFromAdjTime(adjTime: Time): ZonedTime {.benign.} =
  1112. let utcDate = newDate(adjTime.seconds * 1000)
  1113. let localDate = newDate(utcDate.getUTCFullYear(), utcDate.getUTCMonth(),
  1114. utcDate.getUTCDate(), utcDate.getUTCHours(), utcDate.getUTCMinutes(),
  1115. utcDate.getUTCSeconds(), 0)
  1116. # This is as dumb as it looks - JS doesn't support years in the range
  1117. # 0-99 in the constructor because they are assumed to be 19xx...
  1118. # Because JS doesn't support timezone history,
  1119. # it doesn't really matter in practice.
  1120. if utcDate.getUTCFullYear() in 0 .. 99:
  1121. localDate.setFullYear(utcDate.getUTCFullYear())
  1122. result.utcOffset = localDate.getTimezoneOffset() * secondsInMin
  1123. result.time = adjTime + initDuration(seconds = result.utcOffset)
  1124. result.isDst = false
  1125. else:
  1126. proc toAdjUnix(tm: Tm): int64 =
  1127. let epochDay = toEpochDay(tm.tm_mday, (tm.tm_mon + 1).Month,
  1128. tm.tm_year.int + 1900)
  1129. result = epochDay * secondsInDay
  1130. result.inc tm.tm_hour * secondsInHour
  1131. result.inc tm.tm_min * 60
  1132. result.inc tm.tm_sec
  1133. proc getLocalOffsetAndDst(unix: int64): tuple[offset: int, dst: bool] =
  1134. # Windows can't handle unix < 0, so we fall back to unix = 0.
  1135. # FIXME: This should be improved by falling back to the WinAPI instead.
  1136. when defined(windows):
  1137. if unix < 0:
  1138. var a = 0.CTime
  1139. let tmPtr = localtime(a)
  1140. if not tmPtr.isNil:
  1141. let tm = tmPtr[]
  1142. return ((0 - tm.toAdjUnix).int, false)
  1143. return (0, false)
  1144. # In case of a 32-bit time_t, we fallback to the closest available
  1145. # timezone information.
  1146. var a = clamp(unix, low(CTime).int64, high(CTime).int64).CTime
  1147. let tmPtr = localtime(a)
  1148. if not tmPtr.isNil:
  1149. let tm = tmPtr[]
  1150. return ((a.int64 - tm.toAdjUnix).int, tm.tm_isdst > 0)
  1151. return (0, false)
  1152. proc localZonedTimeFromTime(time: Time): ZonedTime {.benign.} =
  1153. let (offset, dst) = getLocalOffsetAndDst(time.seconds)
  1154. result.time = time
  1155. result.utcOffset = offset
  1156. result.isDst = dst
  1157. proc localZonedTimeFromAdjTime(adjTime: Time): ZonedTime {.benign.} =
  1158. var adjUnix = adjTime.seconds
  1159. let past = adjUnix - secondsInDay
  1160. let (pastOffset, _) = getLocalOffsetAndDst(past)
  1161. let future = adjUnix + secondsInDay
  1162. let (futureOffset, _) = getLocalOffsetAndDst(future)
  1163. var utcOffset: int
  1164. if pastOffset == futureOffset:
  1165. utcOffset = pastOffset.int
  1166. else:
  1167. if pastOffset > futureOffset:
  1168. adjUnix -= secondsInHour
  1169. adjUnix += pastOffset
  1170. utcOffset = getLocalOffsetAndDst(adjUnix).offset
  1171. # This extra roundtrip is needed to normalize any impossible datetimes
  1172. # as a result of offset changes (normally due to dst)
  1173. let utcUnix = adjTime.seconds + utcOffset
  1174. let (finalOffset, dst) = getLocalOffsetAndDst(utcUnix)
  1175. result.time = initTime(utcUnix, adjTime.nanosecond)
  1176. result.utcOffset = finalOffset
  1177. result.isDst = dst
  1178. proc utcTzInfo(time: Time): ZonedTime =
  1179. ZonedTime(utcOffset: 0, isDst: false, time: time)
  1180. var utcInstance {.threadvar.}: Timezone
  1181. var localInstance {.threadvar.}: Timezone
  1182. proc utc*(): Timezone =
  1183. ## Get the `Timezone` implementation for the UTC timezone.
  1184. runnableExamples:
  1185. doAssert now().utc.timezone == utc()
  1186. doAssert utc().name == "Etc/UTC"
  1187. if utcInstance.isNil:
  1188. utcInstance = newTimezone("Etc/UTC", utcTzInfo, utcTzInfo)
  1189. result = utcInstance
  1190. proc local*(): Timezone =
  1191. ## Get the `Timezone` implementation for the local timezone.
  1192. runnableExamples:
  1193. doAssert now().timezone == local()
  1194. doAssert local().name == "LOCAL"
  1195. if localInstance.isNil:
  1196. localInstance = newTimezone("LOCAL", localZonedTimeFromTime,
  1197. localZonedTimeFromAdjTime)
  1198. result = localInstance
  1199. proc utc*(dt: DateTime): DateTime =
  1200. ## Shorthand for `dt.inZone(utc())`.
  1201. dt.inZone(utc())
  1202. proc local*(dt: DateTime): DateTime =
  1203. ## Shorthand for `dt.inZone(local())`.
  1204. dt.inZone(local())
  1205. proc utc*(t: Time): DateTime =
  1206. ## Shorthand for `t.inZone(utc())`.
  1207. t.inZone(utc())
  1208. proc local*(t: Time): DateTime =
  1209. ## Shorthand for `t.inZone(local())`.
  1210. t.inZone(local())
  1211. proc now*(): DateTime {.tags: [TimeEffect], benign.} =
  1212. ## Get the current time as a `DateTime` in the local timezone.
  1213. ## Shorthand for `getTime().local`.
  1214. ##
  1215. ## .. warning:: Unsuitable for benchmarking, use `monotimes.getMonoTime` or
  1216. ## `cpuTime` instead, depending on the use case.
  1217. getTime().local
  1218. proc dateTime*(year: int, month: Month, monthday: MonthdayRange,
  1219. hour: HourRange = 0, minute: MinuteRange = 0, second: SecondRange = 0,
  1220. nanosecond: NanosecondRange = 0,
  1221. zone: Timezone = local()): DateTime =
  1222. ## Create a new `DateTime <#DateTime>`_ in the specified timezone.
  1223. runnableExamples:
  1224. assert $dateTime(2017, mMar, 30, zone = utc()) == "2017-03-30T00:00:00Z"
  1225. assertValidDate monthday, month, year
  1226. let dt = DateTime(
  1227. monthdayZero: monthday,
  1228. year: year,
  1229. monthZero: month.int,
  1230. hour: hour,
  1231. minute: minute,
  1232. second: second,
  1233. nanosecond: nanosecond
  1234. )
  1235. result = initDateTime(zone.zonedTimeFromAdjTime(dt.toAdjTime), zone)
  1236. proc initDateTime*(monthday: MonthdayRange, month: Month, year: int,
  1237. hour: HourRange, minute: MinuteRange, second: SecondRange,
  1238. nanosecond: NanosecondRange,
  1239. zone: Timezone = local()): DateTime {.deprecated: "use `dateTime`".} =
  1240. ## Create a new `DateTime <#DateTime>`_ in the specified timezone.
  1241. runnableExamples("--warning:deprecated:off"):
  1242. assert $initDateTime(30, mMar, 2017, 00, 00, 00, 00, utc()) == "2017-03-30T00:00:00Z"
  1243. dateTime(year, month, monthday, hour, minute, second, nanosecond, zone)
  1244. proc initDateTime*(monthday: MonthdayRange, month: Month, year: int,
  1245. hour: HourRange, minute: MinuteRange, second: SecondRange,
  1246. zone: Timezone = local()): DateTime {.deprecated: "use `dateTime`".} =
  1247. ## Create a new `DateTime <#DateTime>`_ in the specified timezone.
  1248. runnableExamples("--warning:deprecated:off"):
  1249. assert $initDateTime(30, mMar, 2017, 00, 00, 00, utc()) == "2017-03-30T00:00:00Z"
  1250. dateTime(year, month, monthday, hour, minute, second, 0, zone)
  1251. proc `+`*(dt: DateTime, dur: Duration): DateTime =
  1252. runnableExamples:
  1253. let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
  1254. let dur = initDuration(hours = 5)
  1255. doAssert $(dt + dur) == "2017-03-30T05:00:00Z"
  1256. (dt.toTime + dur).inZone(dt.timezone)
  1257. proc `-`*(dt: DateTime, dur: Duration): DateTime =
  1258. runnableExamples:
  1259. let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
  1260. let dur = initDuration(days = 5)
  1261. doAssert $(dt - dur) == "2017-03-25T00:00:00Z"
  1262. (dt.toTime - dur).inZone(dt.timezone)
  1263. proc `-`*(dt1, dt2: DateTime): Duration =
  1264. ## Compute the duration between `dt1` and `dt2`.
  1265. runnableExamples:
  1266. let dt1 = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
  1267. let dt2 = dateTime(2017, mMar, 25, 00, 00, 00, 00, utc())
  1268. doAssert dt1 - dt2 == initDuration(days = 5)
  1269. dt1.toTime - dt2.toTime
  1270. proc `<`*(a, b: DateTime): bool =
  1271. ## Returns true if `a` happened before `b`.
  1272. return a.toTime < b.toTime
  1273. proc `<=`*(a, b: DateTime): bool =
  1274. ## Returns true if `a` happened before or at the same time as `b`.
  1275. return a.toTime <= b.toTime
  1276. proc `==`*(a, b: DateTime): bool =
  1277. ## Returns true if `a` and `b` represent the same point in time.
  1278. if not a.isInitialized: not b.isInitialized
  1279. elif not b.isInitialized: false
  1280. else: a.toTime == b.toTime
  1281. proc `+=`*(a: var DateTime, b: Duration) =
  1282. a = a + b
  1283. proc `-=`*(a: var DateTime, b: Duration) =
  1284. a = a - b
  1285. proc getDateStr*(dt = now()): string {.rtl, extern: "nt$1", tags: [TimeEffect].} =
  1286. ## Gets the current local date as a string of the format `YYYY-MM-DD`.
  1287. runnableExamples:
  1288. echo getDateStr(now() - 1.months)
  1289. assertDateTimeInitialized dt
  1290. result = newStringOfCap(10) # len("YYYY-MM-DD") == 10
  1291. result.addInt dt.year
  1292. result.add '-'
  1293. result.add intToStr(dt.monthZero, 2)
  1294. result.add '-'
  1295. result.add intToStr(dt.monthday, 2)
  1296. proc getClockStr*(dt = now()): string {.rtl, extern: "nt$1", tags: [TimeEffect].} =
  1297. ## Gets the current local clock time as a string of the format `HH:mm:ss`.
  1298. runnableExamples:
  1299. echo getClockStr(now() - 1.hours)
  1300. assertDateTimeInitialized dt
  1301. result = newStringOfCap(8) # len("HH:mm:ss") == 8
  1302. result.add intToStr(dt.hour, 2)
  1303. result.add ':'
  1304. result.add intToStr(dt.minute, 2)
  1305. result.add ':'
  1306. result.add intToStr(dt.second, 2)
  1307. #
  1308. # Iso week forward declarations
  1309. #
  1310. proc initDateTime*(weekday: WeekDay, isoweek: IsoWeekRange, isoyear: IsoYear,
  1311. hour: HourRange, minute: MinuteRange, second: SecondRange,
  1312. nanosecond: NanosecondRange,
  1313. zone: Timezone = local()): DateTime {.gcsafe, raises: [], tags: [], since: (1, 5).}
  1314. proc initDateTime*(weekday: WeekDay, isoweek: IsoWeekRange, isoyear: IsoYear,
  1315. hour: HourRange, minute: MinuteRange, second: SecondRange,
  1316. zone: Timezone = local()): DateTime {.gcsafe, raises: [], tags: [], since: (1, 5).}
  1317. #
  1318. # TimeFormat
  1319. #
  1320. when defined(nimHasStyleChecks):
  1321. {.push styleChecks: off.}
  1322. type
  1323. DateTimeLocale* = object
  1324. MMM*: array[mJan..mDec, string]
  1325. MMMM*: array[mJan..mDec, string]
  1326. ddd*: array[dMon..dSun, string]
  1327. dddd*: array[dMon..dSun, string]
  1328. when defined(nimHasStyleChecks):
  1329. {.pop.}
  1330. type
  1331. AmPm = enum
  1332. apUnknown, apAm, apPm
  1333. Era = enum
  1334. eraUnknown, eraAd, eraBc
  1335. ParsedTime = object
  1336. amPm: AmPm
  1337. era: Era
  1338. year: Option[int]
  1339. month: Option[int]
  1340. monthday: Option[int]
  1341. isoyear: Option[int]
  1342. yearweek: Option[int]
  1343. weekday: Option[WeekDay]
  1344. utcOffset: Option[int]
  1345. # '0' as default for these work fine
  1346. # so no need for `Option`.
  1347. hour: int
  1348. minute: int
  1349. second: int
  1350. nanosecond: int
  1351. FormatTokenKind = enum
  1352. tkPattern, tkLiteral
  1353. FormatPattern {.pure.} = enum
  1354. d, dd, ddd, dddd
  1355. GG, GGGG
  1356. h, hh, H, HH
  1357. m, mm, M, MM, MMM, MMMM
  1358. s, ss
  1359. fff, ffffff, fffffffff
  1360. t, tt
  1361. yy, yyyy
  1362. YYYY
  1363. uuuu
  1364. UUUU
  1365. V, VV
  1366. z, zz, zzz, zzzz
  1367. ZZZ, ZZZZ
  1368. g
  1369. # This is a special value used to mark literal format values.
  1370. # See the doc comment for `TimeFormat.patterns`.
  1371. Lit
  1372. TimeFormat* = object ## Represents a format for parsing and printing
  1373. ## time types.
  1374. ##
  1375. ## To create a new `TimeFormat` use `initTimeFormat proc
  1376. ## <#initTimeFormat,string>`_.
  1377. patterns: seq[byte] ## \
  1378. ## Contains the patterns encoded as bytes.
  1379. ## Literal values are encoded in a special way.
  1380. ## They start with `Lit.byte`, then the length of the literal, then the
  1381. ## raw char values of the literal. For example, the literal `foo` would
  1382. ## be encoded as `@[Lit.byte, 3.byte, 'f'.byte, 'o'.byte, 'o'.byte]`.
  1383. formatStr: string
  1384. TimeParseError* = object of ValueError ## \
  1385. ## Raised when parsing input using a `TimeFormat` fails.
  1386. TimeFormatParseError* = object of ValueError ## \
  1387. ## Raised when parsing a `TimeFormat` string fails.
  1388. const
  1389. DefaultLocale* = DateTimeLocale(
  1390. MMM: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
  1391. "Nov", "Dec"],
  1392. MMMM: ["January", "February", "March", "April", "May", "June", "July",
  1393. "August", "September", "October", "November", "December"],
  1394. ddd: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  1395. dddd: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
  1396. "Sunday"],
  1397. )
  1398. FormatLiterals = {' ', '-', '/', ':', '(', ')', '[', ']', ','}
  1399. proc `$`*(f: TimeFormat): string =
  1400. ## Returns the format string that was used to construct `f`.
  1401. runnableExamples:
  1402. let f = initTimeFormat("yyyy-MM-dd")
  1403. doAssert $f == "yyyy-MM-dd"
  1404. f.formatStr
  1405. proc raiseParseException(f: TimeFormat, input: string, msg: string) =
  1406. raise newException(TimeParseError,
  1407. "Failed to parse '" & input & "' with format '" & $f &
  1408. "'. " & msg)
  1409. proc parseInt(s: string, b: var int, start = 0, maxLen = int.high,
  1410. allowSign = false): int =
  1411. var sign = -1
  1412. var i = start
  1413. let stop = start + min(s.high - start + 1, maxLen) - 1
  1414. if allowSign and i <= stop:
  1415. if s[i] == '+':
  1416. inc(i)
  1417. elif s[i] == '-':
  1418. inc(i)
  1419. sign = 1
  1420. if i <= stop and s[i] in {'0'..'9'}:
  1421. b = 0
  1422. while i <= stop and s[i] in {'0'..'9'}:
  1423. let c = ord(s[i]) - ord('0')
  1424. if b >= (low(int) + c) div 10:
  1425. b = b * 10 - c
  1426. else:
  1427. return 0
  1428. inc(i)
  1429. if sign == -1 and b == low(int):
  1430. return 0
  1431. b = b * sign
  1432. result = i - start
  1433. iterator tokens(f: string): tuple[kind: FormatTokenKind, token: string] =
  1434. var i = 0
  1435. var currToken = ""
  1436. template yieldCurrToken() =
  1437. if currToken.len != 0:
  1438. yield (tkPattern, currToken)
  1439. currToken = ""
  1440. while i < f.len:
  1441. case f[i]
  1442. of '\'':
  1443. yieldCurrToken()
  1444. if i.succ < f.len and f[i.succ] == '\'':
  1445. yield (tkLiteral, "'")
  1446. i.inc 2
  1447. else:
  1448. var token = ""
  1449. inc(i) # Skip '
  1450. while i < f.len and f[i] != '\'':
  1451. token.add f[i]
  1452. i.inc
  1453. if i > f.high:
  1454. raise newException(TimeFormatParseError,
  1455. "Unclosed ' in time format string. " &
  1456. "For a literal ', use ''.")
  1457. i.inc
  1458. yield (tkLiteral, token)
  1459. of FormatLiterals:
  1460. yieldCurrToken()
  1461. yield (tkLiteral, $f[i])
  1462. i.inc
  1463. else:
  1464. # Check if the letter being added matches previous accumulated buffer.
  1465. if currToken.len == 0 or currToken[0] == f[i]:
  1466. currToken.add(f[i])
  1467. i.inc
  1468. else:
  1469. yield (tkPattern, currToken)
  1470. currToken = $f[i]
  1471. i.inc
  1472. yieldCurrToken()
  1473. proc stringToPattern(str: string): FormatPattern =
  1474. case str
  1475. of "d": result = d
  1476. of "dd": result = dd
  1477. of "ddd": result = ddd
  1478. of "dddd": result = dddd
  1479. of "GG": result = GG
  1480. of "GGGG": result = GGGG
  1481. of "h": result = h
  1482. of "hh": result = hh
  1483. of "H": result = H
  1484. of "HH": result = HH
  1485. of "m": result = m
  1486. of "mm": result = mm
  1487. of "M": result = M
  1488. of "MM": result = MM
  1489. of "MMM": result = MMM
  1490. of "MMMM": result = MMMM
  1491. of "s": result = s
  1492. of "ss": result = ss
  1493. of "fff": result = fff
  1494. of "ffffff": result = ffffff
  1495. of "fffffffff": result = fffffffff
  1496. of "t": result = t
  1497. of "tt": result = tt
  1498. of "yy": result = yy
  1499. of "yyyy": result = yyyy
  1500. of "YYYY": result = YYYY
  1501. of "uuuu": result = uuuu
  1502. of "UUUU": result = UUUU
  1503. of "V": result = V
  1504. of "VV": result = VV
  1505. of "z": result = z
  1506. of "zz": result = zz
  1507. of "zzz": result = zzz
  1508. of "zzzz": result = zzzz
  1509. of "ZZZ": result = ZZZ
  1510. of "ZZZZ": result = ZZZZ
  1511. of "g": result = g
  1512. else: raise newException(TimeFormatParseError,
  1513. "'" & str & "' is not a valid pattern")
  1514. proc initTimeFormat*(format: string): TimeFormat =
  1515. ## Construct a new time format for parsing & formatting time types.
  1516. ##
  1517. ## See `Parsing and formatting dates`_ for documentation of the
  1518. ## `format` argument.
  1519. runnableExamples:
  1520. let f = initTimeFormat("yyyy-MM-dd")
  1521. doAssert "2000-01-01" == "2000-01-01".parse(f).format(f)
  1522. result.formatStr = format
  1523. result.patterns = @[]
  1524. for kind, token in format.tokens:
  1525. case kind
  1526. of tkLiteral:
  1527. case token
  1528. else:
  1529. result.patterns.add(FormatPattern.Lit.byte)
  1530. if token.len > 255:
  1531. raise newException(TimeFormatParseError,
  1532. "Format literal is to long:" & token)
  1533. result.patterns.add(token.len.byte)
  1534. for c in token:
  1535. result.patterns.add(c.byte)
  1536. of tkPattern:
  1537. result.patterns.add(stringToPattern(token).byte)
  1538. proc formatPattern(dt: DateTime, pattern: FormatPattern, result: var string,
  1539. loc: DateTimeLocale) =
  1540. template yearOfEra(dt: DateTime): int =
  1541. if dt.year <= 0: abs(dt.year) + 1 else: dt.year
  1542. case pattern
  1543. of d:
  1544. result.add $dt.monthday
  1545. of dd:
  1546. result.add dt.monthday.intToStr(2)
  1547. of ddd:
  1548. result.add loc.ddd[dt.weekday]
  1549. of dddd:
  1550. result.add loc.dddd[dt.weekday]
  1551. of GG:
  1552. result.add (dt.getIsoWeekAndYear.isoyear.int mod 100).intToStr(2)
  1553. of GGGG:
  1554. result.add $dt.getIsoWeekAndYear.isoyear
  1555. of h:
  1556. result.add(
  1557. if dt.hour == 0: "12"
  1558. elif dt.hour > 12: $(dt.hour - 12)
  1559. else: $dt.hour
  1560. )
  1561. of hh:
  1562. result.add(
  1563. if dt.hour == 0: "12"
  1564. elif dt.hour > 12: (dt.hour - 12).intToStr(2)
  1565. else: dt.hour.intToStr(2)
  1566. )
  1567. of H:
  1568. result.add $dt.hour
  1569. of HH:
  1570. result.add dt.hour.intToStr(2)
  1571. of m:
  1572. result.add $dt.minute
  1573. of mm:
  1574. result.add dt.minute.intToStr(2)
  1575. of M:
  1576. result.add $ord(dt.month)
  1577. of MM:
  1578. result.add ord(dt.month).intToStr(2)
  1579. of MMM:
  1580. result.add loc.MMM[dt.month]
  1581. of MMMM:
  1582. result.add loc.MMMM[dt.month]
  1583. of s:
  1584. result.add $dt.second
  1585. of ss:
  1586. result.add dt.second.intToStr(2)
  1587. of fff:
  1588. result.add(intToStr(convert(Nanoseconds, Milliseconds, dt.nanosecond), 3))
  1589. of ffffff:
  1590. result.add(intToStr(convert(Nanoseconds, Microseconds, dt.nanosecond), 6))
  1591. of fffffffff:
  1592. result.add(intToStr(dt.nanosecond, 9))
  1593. of t:
  1594. result.add if dt.hour >= 12: "P" else: "A"
  1595. of tt:
  1596. result.add if dt.hour >= 12: "PM" else: "AM"
  1597. of yy:
  1598. result.add (dt.yearOfEra mod 100).intToStr(2)
  1599. of yyyy:
  1600. let year = dt.yearOfEra
  1601. if year < 10000:
  1602. result.add year.intToStr(4)
  1603. else:
  1604. result.add '+' & $year
  1605. of YYYY:
  1606. if dt.year < 1:
  1607. result.add $(abs(dt.year) + 1)
  1608. else:
  1609. result.add $dt.year
  1610. of uuuu:
  1611. let year = dt.year
  1612. if year < 10000 or year < 0:
  1613. result.add year.intToStr(4)
  1614. else:
  1615. result.add '+' & $year
  1616. of UUUU:
  1617. result.add $dt.year
  1618. of V:
  1619. result.add $dt.getIsoWeekAndYear.isoweek
  1620. of VV:
  1621. result.add dt.getIsoWeekAndYear.isoweek.intToStr(2)
  1622. of z, zz, zzz, zzzz, ZZZ, ZZZZ:
  1623. if dt.timezone != nil and dt.timezone.name == "Etc/UTC":
  1624. result.add 'Z'
  1625. else:
  1626. result.add if -dt.utcOffset >= 0: '+' else: '-'
  1627. let absOffset = abs(dt.utcOffset)
  1628. case pattern:
  1629. of z:
  1630. result.add $(absOffset div 3600)
  1631. of zz:
  1632. result.add (absOffset div 3600).intToStr(2)
  1633. of zzz, ZZZ:
  1634. let h = (absOffset div 3600).intToStr(2)
  1635. let m = ((absOffset div 60) mod 60).intToStr(2)
  1636. let sep = if pattern == zzz: ":" else: ""
  1637. result.add h & sep & m
  1638. of zzzz, ZZZZ:
  1639. let absOffset = abs(dt.utcOffset)
  1640. let h = (absOffset div 3600).intToStr(2)
  1641. let m = ((absOffset div 60) mod 60).intToStr(2)
  1642. let s = (absOffset mod 60).intToStr(2)
  1643. let sep = if pattern == zzzz: ":" else: ""
  1644. result.add h & sep & m & sep & s
  1645. else: assert false
  1646. of g:
  1647. result.add if dt.year < 1: "BC" else: "AD"
  1648. of Lit: assert false # Can't happen
  1649. proc parsePattern(input: string, pattern: FormatPattern, i: var int,
  1650. parsed: var ParsedTime, loc: DateTimeLocale): bool =
  1651. template takeInt(allowedWidth: Slice[int], allowSign = false): int =
  1652. var sv = 0
  1653. var pd = parseInt(input, sv, i, allowedWidth.b, allowSign)
  1654. if pd < allowedWidth.a:
  1655. return false
  1656. i.inc pd
  1657. sv
  1658. template contains[T](t: typedesc[T], i: int): bool =
  1659. i in low(t)..high(t)
  1660. result = true
  1661. case pattern
  1662. of d:
  1663. let monthday = takeInt(1..2)
  1664. parsed.monthday = some(monthday)
  1665. result = monthday in MonthdayRange
  1666. of dd:
  1667. let monthday = takeInt(2..2)
  1668. parsed.monthday = some(monthday)
  1669. result = monthday in MonthdayRange
  1670. of ddd:
  1671. result = false
  1672. for d, v in loc.ddd:
  1673. if input.substr(i, i+v.len-1).cmpIgnoreCase(v) == 0:
  1674. parsed.weekday = some(d.WeekDay)
  1675. result = true
  1676. i.inc v.len
  1677. break
  1678. of dddd:
  1679. result = false
  1680. for d, v in loc.dddd:
  1681. if input.substr(i, i+v.len-1).cmpIgnoreCase(v) == 0:
  1682. parsed.weekday = some(d.WeekDay)
  1683. result = true
  1684. i.inc v.len
  1685. break
  1686. of GG:
  1687. # Assumes current century
  1688. var isoyear = takeInt(2..2)
  1689. var thisCen = now().year div 100
  1690. parsed.isoyear = some(thisCen*100 + isoyear)
  1691. result = isoyear > 0
  1692. of GGGG:
  1693. let isoyear = takeInt(1..high(int))
  1694. parsed.isoyear = some(isoyear)
  1695. result = isoyear > 0
  1696. of h, H:
  1697. parsed.hour = takeInt(1..2)
  1698. result = parsed.hour in HourRange
  1699. of hh, HH:
  1700. parsed.hour = takeInt(2..2)
  1701. result = parsed.hour in HourRange
  1702. of m:
  1703. parsed.minute = takeInt(1..2)
  1704. result = parsed.hour in MinuteRange
  1705. of mm:
  1706. parsed.minute = takeInt(2..2)
  1707. result = parsed.hour in MinuteRange
  1708. of M:
  1709. let month = takeInt(1..2)
  1710. result = month in 1..12
  1711. parsed.month = some(month)
  1712. of MM:
  1713. let month = takeInt(2..2)
  1714. result = month in 1..12
  1715. parsed.month = some(month)
  1716. of MMM:
  1717. result = false
  1718. for n, v in loc.MMM:
  1719. if input.substr(i, i+v.len-1).cmpIgnoreCase(v) == 0:
  1720. result = true
  1721. i.inc v.len
  1722. parsed.month = some(n.int)
  1723. break
  1724. of MMMM:
  1725. result = false
  1726. for n, v in loc.MMMM:
  1727. if input.substr(i, i+v.len-1).cmpIgnoreCase(v) == 0:
  1728. result = true
  1729. i.inc v.len
  1730. parsed.month = some(n.int)
  1731. break
  1732. of s:
  1733. parsed.second = takeInt(1..2)
  1734. of ss:
  1735. parsed.second = takeInt(2..2)
  1736. of fff, ffffff, fffffffff:
  1737. let len = ($pattern).len
  1738. let v = takeInt(len..len)
  1739. parsed.nanosecond = v * 10^(9 - len)
  1740. result = parsed.nanosecond in NanosecondRange
  1741. of t:
  1742. case input[i]:
  1743. of 'P':
  1744. parsed.amPm = apPm
  1745. of 'A':
  1746. parsed.amPm = apAm
  1747. else:
  1748. result = false
  1749. i.inc 1
  1750. of tt:
  1751. if input.substr(i, i+1).cmpIgnoreCase("AM") == 0:
  1752. parsed.amPm = apAm
  1753. i.inc 2
  1754. elif input.substr(i, i+1).cmpIgnoreCase("PM") == 0:
  1755. parsed.amPm = apPm
  1756. i.inc 2
  1757. else:
  1758. result = false
  1759. of yy:
  1760. # Assumes current century
  1761. var year = takeInt(2..2)
  1762. var thisCen = now().year div 100
  1763. parsed.year = some(thisCen*100 + year)
  1764. result = year > 0
  1765. of yyyy:
  1766. let year =
  1767. if input[i] in {'+', '-'}:
  1768. takeInt(4..high(int), allowSign = true)
  1769. else:
  1770. takeInt(4..4)
  1771. result = year > 0
  1772. parsed.year = some(year)
  1773. of YYYY:
  1774. let year = takeInt(1..high(int))
  1775. parsed.year = some(year)
  1776. result = year > 0
  1777. of uuuu:
  1778. let year =
  1779. if input[i] in {'+', '-'}:
  1780. takeInt(4..high(int), allowSign = true)
  1781. else:
  1782. takeInt(4..4)
  1783. parsed.year = some(year)
  1784. of UUUU:
  1785. parsed.year = some(takeInt(1..high(int), allowSign = true))
  1786. of V:
  1787. let yearweek = takeInt(1..2)
  1788. parsed.yearweek = some(yearweek)
  1789. result = yearweek in IsoWeekRange
  1790. of VV:
  1791. let yearweek = takeInt(2..2)
  1792. parsed.yearweek = some(yearweek)
  1793. result = yearweek in IsoWeekRange
  1794. of z, zz, zzz, zzzz, ZZZ, ZZZZ:
  1795. case input[i]
  1796. of '+', '-':
  1797. let sign = if input[i] == '-': 1 else: -1
  1798. i.inc
  1799. var offset = 0
  1800. case pattern
  1801. of z:
  1802. offset = takeInt(1..2) * 3600
  1803. of zz:
  1804. offset = takeInt(2..2) * 3600
  1805. of zzz, ZZZ:
  1806. offset.inc takeInt(2..2) * 3600
  1807. if pattern == zzz:
  1808. if input[i] != ':':
  1809. return false
  1810. i.inc
  1811. offset.inc takeInt(2..2) * 60
  1812. of zzzz, ZZZZ:
  1813. offset.inc takeInt(2..2) * 3600
  1814. if pattern == zzzz:
  1815. if input[i] != ':':
  1816. return false
  1817. i.inc
  1818. offset.inc takeInt(2..2) * 60
  1819. if pattern == zzzz:
  1820. if input[i] != ':':
  1821. return false
  1822. i.inc
  1823. offset.inc takeInt(2..2)
  1824. else: assert false
  1825. parsed.utcOffset = some(offset * sign)
  1826. of 'Z':
  1827. parsed.utcOffset = some(0)
  1828. i.inc
  1829. else:
  1830. result = false
  1831. of g:
  1832. if input.substr(i, i+1).cmpIgnoreCase("BC") == 0:
  1833. parsed.era = eraBc
  1834. i.inc 2
  1835. elif input.substr(i, i+1).cmpIgnoreCase("AD") == 0:
  1836. parsed.era = eraAd
  1837. i.inc 2
  1838. else:
  1839. result = false
  1840. of Lit: doAssert false, "Can't happen"
  1841. proc toDateTime(p: ParsedTime, zone: Timezone, f: TimeFormat,
  1842. input: string): DateTime =
  1843. var year = p.year.get(0)
  1844. var month = p.month.get(1).Month
  1845. var monthday = p.monthday.get(1)
  1846. year =
  1847. case p.era
  1848. of eraUnknown:
  1849. year
  1850. of eraBc:
  1851. if year < 1:
  1852. raiseParseException(f, input,
  1853. "Expected year to be positive " &
  1854. "(use 'UUUU' or 'uuuu' for negative years).")
  1855. -year + 1
  1856. of eraAd:
  1857. if year < 1:
  1858. raiseParseException(f, input,
  1859. "Expected year to be positive " &
  1860. "(use 'UUUU' or 'uuuu' for negative years).")
  1861. year
  1862. let hour =
  1863. case p.amPm
  1864. of apUnknown:
  1865. p.hour
  1866. of apAm:
  1867. if p.hour notin 1..12:
  1868. raiseParseException(f, input,
  1869. "AM/PM time must be in the interval 1..12")
  1870. if p.hour == 12: 0 else: p.hour
  1871. of apPm:
  1872. if p.hour notin 1..12:
  1873. raiseParseException(f, input,
  1874. "AM/PM time must be in the interval 1..12")
  1875. if p.hour == 12: p.hour else: p.hour + 12
  1876. let minute = p.minute
  1877. let second = p.second
  1878. let nanosecond = p.nanosecond
  1879. if monthday > getDaysInMonth(month, year):
  1880. raiseParseException(f, input,
  1881. $year & "-" & ord(month).intToStr(2) &
  1882. "-" & $monthday & " is not a valid date")
  1883. if p.utcOffset.isNone:
  1884. # No timezone parsed - assume timezone is `zone`
  1885. result = dateTime(year, month, monthday, hour, minute, second, nanosecond, zone)
  1886. else:
  1887. # Otherwise convert to `zone`
  1888. result = (dateTime(year, month, monthday, hour, minute, second, nanosecond, utc()).toTime +
  1889. initDuration(seconds = p.utcOffset.get())).inZone(zone)
  1890. proc toDateTimeByWeek(p: ParsedTime, zone: Timezone, f: TimeFormat,
  1891. input: string): DateTime =
  1892. var isoyear = p.isoyear.get(0)
  1893. var yearweek = p.yearweek.get(1)
  1894. var weekday = p.weekday.get(dMon)
  1895. if p.amPm != apUnknown:
  1896. raiseParseException(f, input, "Parsing iso weekyear dates does not support am/pm")
  1897. if p.year.isSome:
  1898. raiseParseException(f, input, "Use iso-year GG or GGGG as year with iso week number")
  1899. if p.month.isSome:
  1900. raiseParseException(f, input, "Use either iso week number V or VV or month")
  1901. if p.monthday.isSome:
  1902. raiseParseException(f, input, "Use weekday ddd or dddd as day with with iso week number")
  1903. if p.isoyear.isNone:
  1904. raiseParseException(f, input, "Need iso-year with week number")
  1905. let hour = p.hour
  1906. let minute = p.minute
  1907. let second = p.second
  1908. let nanosecond = p.nanosecond
  1909. if p.utcOffset.isNone:
  1910. result = initDateTime(weekday, yearweek.IsoWeekRange, isoyear.IsoYear, hour, minute, second, nanosecond, zone)
  1911. else:
  1912. result = (initDateTime(weekday, yearweek.IsoWeekRange, isoyear.IsoYear, hour, minute, second, nanosecond, zone).toTime +
  1913. initDuration(seconds = p.utcOffset.get())).inZone(zone)
  1914. proc format*(dt: DateTime, f: TimeFormat,
  1915. loc: DateTimeLocale = DefaultLocale): string {.raises: [].} =
  1916. ## Format `dt` using the format specified by `f`.
  1917. runnableExamples:
  1918. let f = initTimeFormat("yyyy-MM-dd")
  1919. let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
  1920. doAssert "2000-01-01" == dt.format(f)
  1921. assertDateTimeInitialized dt
  1922. result = ""
  1923. var idx = 0
  1924. while idx <= f.patterns.high:
  1925. case f.patterns[idx].FormatPattern
  1926. of Lit:
  1927. idx.inc
  1928. let len = f.patterns[idx]
  1929. for i in 1'u8..len:
  1930. idx.inc
  1931. result.add f.patterns[idx].char
  1932. idx.inc
  1933. else:
  1934. formatPattern(dt, f.patterns[idx].FormatPattern, result = result, loc = loc)
  1935. idx.inc
  1936. proc format*(dt: DateTime, f: string, loc: DateTimeLocale = DefaultLocale): string
  1937. {.raises: [TimeFormatParseError].} =
  1938. ## Shorthand for constructing a `TimeFormat` and using it to format `dt`.
  1939. ##
  1940. ## See `Parsing and formatting dates`_ for documentation of the
  1941. ## `format` argument.
  1942. runnableExamples:
  1943. let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
  1944. doAssert "2000-01-01" == format(dt, "yyyy-MM-dd")
  1945. let dtFormat = initTimeFormat(f)
  1946. result = dt.format(dtFormat, loc)
  1947. proc format*(dt: DateTime, f: static[string]): string {.raises: [].} =
  1948. ## Overload that validates `format` at compile time.
  1949. const f2 = initTimeFormat(f)
  1950. result = dt.format(f2)
  1951. proc formatValue*(result: var string; value: DateTime | Time, specifier: string) =
  1952. ## adapter for strformat. Not intended to be called directly.
  1953. result.add format(value,
  1954. if specifier.len == 0: "yyyy-MM-dd'T'HH:mm:sszzz" else: specifier)
  1955. proc format*(time: Time, f: string, zone: Timezone = local()): string
  1956. {.raises: [TimeFormatParseError].} =
  1957. ## Shorthand for constructing a `TimeFormat` and using it to format
  1958. ## `time`. Will use the timezone specified by `zone`.
  1959. ##
  1960. ## See `Parsing and formatting dates`_ for documentation of the
  1961. ## `f` argument.
  1962. runnableExamples:
  1963. var dt = dateTime(1970, mJan, 01, 00, 00, 00, 00, utc())
  1964. var tm = dt.toTime()
  1965. doAssert format(tm, "yyyy-MM-dd'T'HH:mm:ss", utc()) == "1970-01-01T00:00:00"
  1966. time.inZone(zone).format(f)
  1967. proc format*(time: Time, f: static[string], zone: Timezone = local()): string
  1968. {.raises: [].} =
  1969. ## Overload that validates `f` at compile time.
  1970. const f2 = initTimeFormat(f)
  1971. result = time.inZone(zone).format(f2)
  1972. proc parse*(input: string, f: TimeFormat, zone: Timezone = local(),
  1973. loc: DateTimeLocale = DefaultLocale): DateTime {.parseRaises.} =
  1974. ## Parses `input` as a `DateTime` using the format specified by `f`.
  1975. ## If no UTC offset was parsed, then `input` is assumed to be specified in
  1976. ## the `zone` timezone. If a UTC offset was parsed, the result will be
  1977. ## converted to the `zone` timezone.
  1978. ##
  1979. ## Month and day names from the passed in `loc` are used.
  1980. runnableExamples:
  1981. let f = initTimeFormat("yyyy-MM-dd")
  1982. let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
  1983. doAssert dt == "2000-01-01".parse(f, utc())
  1984. var inpIdx = 0 # Input index
  1985. var patIdx = 0 # Pattern index
  1986. var parsed: ParsedTime
  1987. while inpIdx <= input.high and patIdx <= f.patterns.high:
  1988. let pattern = f.patterns[patIdx].FormatPattern
  1989. case pattern
  1990. of Lit:
  1991. patIdx.inc
  1992. let len = f.patterns[patIdx]
  1993. patIdx.inc
  1994. for _ in 1'u8..len:
  1995. if input[inpIdx] != f.patterns[patIdx].char:
  1996. raiseParseException(f, input,
  1997. "Unexpected character: " & input[inpIdx])
  1998. inpIdx.inc
  1999. patIdx.inc
  2000. else:
  2001. if not parsePattern(input, pattern, inpIdx, parsed, loc):
  2002. raiseParseException(f, input, "Failed on pattern '" & $pattern & "'")
  2003. patIdx.inc
  2004. if inpIdx <= input.high:
  2005. raiseParseException(f, input,
  2006. "Parsing ended but there was still input remaining")
  2007. if patIdx <= f.patterns.high:
  2008. raiseParseException(f, input,
  2009. "Parsing ended but there was still patterns remaining")
  2010. if parsed.yearweek.isSome:
  2011. result = toDateTimeByWeek(parsed, zone, f, input)
  2012. elif parsed.isoyear.isSome:
  2013. raiseParseException(f, input, "Iso year GG or GGGG require iso week V or VV")
  2014. else:
  2015. result = toDateTime(parsed, zone, f, input)
  2016. proc parse*(input, f: string, tz: Timezone = local(),
  2017. loc: DateTimeLocale = DefaultLocale): DateTime {.parseFormatRaises.} =
  2018. ## Shorthand for constructing a `TimeFormat` and using it to parse
  2019. ## `input` as a `DateTime`.
  2020. ##
  2021. ## See `Parsing and formatting dates`_ for documentation of the
  2022. ## `f` argument.
  2023. runnableExamples:
  2024. let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
  2025. doAssert dt == parse("2000-01-01", "yyyy-MM-dd", utc())
  2026. let dtFormat = initTimeFormat(f)
  2027. result = input.parse(dtFormat, tz, loc = loc)
  2028. proc parse*(input: string, f: static[string], zone: Timezone = local(),
  2029. loc: DateTimeLocale = DefaultLocale): DateTime {.parseRaises.} =
  2030. ## Overload that validates `f` at compile time.
  2031. const f2 = initTimeFormat(f)
  2032. result = input.parse(f2, zone, loc = loc)
  2033. proc parseTime*(input, f: string, zone: Timezone): Time {.parseFormatRaises.} =
  2034. ## Shorthand for constructing a `TimeFormat` and using it to parse
  2035. ## `input` as a `DateTime`, then converting it a `Time`.
  2036. ##
  2037. ## See `Parsing and formatting dates`_ for documentation of the
  2038. ## `format` argument.
  2039. runnableExamples:
  2040. let tStr = "1970-01-01T00:00:00+00:00"
  2041. doAssert parseTime(tStr, "yyyy-MM-dd'T'HH:mm:sszzz", utc()) == fromUnix(0)
  2042. parse(input, f, zone).toTime()
  2043. proc parseTime*(input: string, f: static[string], zone: Timezone): Time
  2044. {.parseRaises.} =
  2045. ## Overload that validates `format` at compile time.
  2046. const f2 = initTimeFormat(f)
  2047. result = input.parse(f2, zone).toTime()
  2048. proc `$`*(dt: DateTime): string {.tags: [], raises: [], benign.} =
  2049. ## Converts a `DateTime` object to a string representation.
  2050. ## It uses the format `yyyy-MM-dd'T'HH:mm:sszzz`.
  2051. runnableExamples:
  2052. let dt = dateTime(2000, mJan, 01, 12, 00, 00, 00, utc())
  2053. doAssert $dt == "2000-01-01T12:00:00Z"
  2054. doAssert $default(DateTime) == "Uninitialized DateTime"
  2055. if not dt.isInitialized:
  2056. result = "Uninitialized DateTime"
  2057. else:
  2058. result = format(dt, "yyyy-MM-dd'T'HH:mm:sszzz")
  2059. proc `$`*(time: Time): string {.tags: [], raises: [], benign.} =
  2060. ## Converts a `Time` value to a string representation. It will use the local
  2061. ## time zone and use the format `yyyy-MM-dd'T'HH:mm:sszzz`.
  2062. runnableExamples:
  2063. let dt = dateTime(1970, mJan, 01, 00, 00, 00, 00, local())
  2064. let tm = dt.toTime()
  2065. doAssert $tm == "1970-01-01T00:00:00" & format(dt, "zzz")
  2066. $time.local
  2067. #
  2068. # TimeInterval
  2069. #
  2070. proc initTimeInterval*(nanoseconds, microseconds, milliseconds,
  2071. seconds, minutes, hours,
  2072. days, weeks, months, years: int = 0): TimeInterval =
  2073. ## Creates a new `TimeInterval <#TimeInterval>`_.
  2074. ##
  2075. ## This proc doesn't perform any normalization! For example,
  2076. ## `initTimeInterval(hours = 24)` and `initTimeInterval(days = 1)` are
  2077. ## not equal.
  2078. ##
  2079. ## You can also use the convenience procedures called `milliseconds`,
  2080. ## `seconds`, `minutes`, `hours`, `days`, `months`, and `years`.
  2081. runnableExamples:
  2082. let day = initTimeInterval(hours = 24)
  2083. let dt = dateTime(2000, mJan, 01, 12, 00, 00, 00, utc())
  2084. doAssert $(dt + day) == "2000-01-02T12:00:00Z"
  2085. doAssert initTimeInterval(hours = 24) != initTimeInterval(days = 1)
  2086. result.nanoseconds = nanoseconds
  2087. result.microseconds = microseconds
  2088. result.milliseconds = milliseconds
  2089. result.seconds = seconds
  2090. result.minutes = minutes
  2091. result.hours = hours
  2092. result.days = days
  2093. result.weeks = weeks
  2094. result.months = months
  2095. result.years = years
  2096. proc `+`*(ti1, ti2: TimeInterval): TimeInterval =
  2097. ## Adds two `TimeInterval` objects together.
  2098. result.nanoseconds = ti1.nanoseconds + ti2.nanoseconds
  2099. result.microseconds = ti1.microseconds + ti2.microseconds
  2100. result.milliseconds = ti1.milliseconds + ti2.milliseconds
  2101. result.seconds = ti1.seconds + ti2.seconds
  2102. result.minutes = ti1.minutes + ti2.minutes
  2103. result.hours = ti1.hours + ti2.hours
  2104. result.days = ti1.days + ti2.days
  2105. result.weeks = ti1.weeks + ti2.weeks
  2106. result.months = ti1.months + ti2.months
  2107. result.years = ti1.years + ti2.years
  2108. proc `-`*(ti: TimeInterval): TimeInterval =
  2109. ## Reverses a time interval
  2110. runnableExamples:
  2111. let day = -initTimeInterval(hours = 24)
  2112. doAssert day.hours == -24
  2113. result = TimeInterval(
  2114. nanoseconds: -ti.nanoseconds,
  2115. microseconds: -ti.microseconds,
  2116. milliseconds: -ti.milliseconds,
  2117. seconds: -ti.seconds,
  2118. minutes: -ti.minutes,
  2119. hours: -ti.hours,
  2120. days: -ti.days,
  2121. weeks: -ti.weeks,
  2122. months: -ti.months,
  2123. years: -ti.years
  2124. )
  2125. proc `-`*(ti1, ti2: TimeInterval): TimeInterval =
  2126. ## Subtracts TimeInterval `ti1` from `ti2`.
  2127. ##
  2128. ## Time components are subtracted one-by-one, see output:
  2129. runnableExamples:
  2130. let ti1 = initTimeInterval(hours = 24)
  2131. let ti2 = initTimeInterval(hours = 4)
  2132. doAssert (ti1 - ti2) == initTimeInterval(hours = 20)
  2133. result = ti1 + (-ti2)
  2134. proc `+=`*(a: var TimeInterval, b: TimeInterval) =
  2135. a = a + b
  2136. proc `-=`*(a: var TimeInterval, b: TimeInterval) =
  2137. a = a - b
  2138. proc isStaticInterval(interval: TimeInterval): bool =
  2139. interval.years == 0 and interval.months == 0 and
  2140. interval.days == 0 and interval.weeks == 0
  2141. proc evaluateStaticInterval(interval: TimeInterval): Duration =
  2142. assert interval.isStaticInterval
  2143. initDuration(nanoseconds = interval.nanoseconds,
  2144. microseconds = interval.microseconds,
  2145. milliseconds = interval.milliseconds,
  2146. seconds = interval.seconds,
  2147. minutes = interval.minutes,
  2148. hours = interval.hours)
  2149. proc between*(startDt, endDt: DateTime): TimeInterval =
  2150. ## Gives the difference between `startDt` and `endDt` as a
  2151. ## `TimeInterval`. The following guarantees about the result is given:
  2152. ##
  2153. ## - All fields will have the same sign.
  2154. ## - If `startDt.timezone == endDt.timezone`, it is guaranteed that
  2155. ## `startDt + between(startDt, endDt) == endDt`.
  2156. ## - If `startDt.timezone != endDt.timezone`, then the result will be
  2157. ## equivalent to `between(startDt.utc, endDt.utc)`.
  2158. runnableExamples:
  2159. var a = dateTime(2015, mMar, 25, 12, 0, 0, 00, utc())
  2160. var b = dateTime(2017, mApr, 1, 15, 0, 15, 00, utc())
  2161. var ti = initTimeInterval(years = 2, weeks = 1, hours = 3, seconds = 15)
  2162. doAssert between(a, b) == ti
  2163. doAssert between(a, b) == -between(b, a)
  2164. if startDt.timezone != endDt.timezone:
  2165. return between(startDt.utc, endDt.utc)
  2166. elif endDt < startDt:
  2167. return -between(endDt, startDt)
  2168. type Date = tuple[year, month, monthday: int]
  2169. var startDate: Date = (startDt.year, startDt.month.ord, startDt.monthday)
  2170. var endDate: Date = (endDt.year, endDt.month.ord, endDt.monthday)
  2171. # Subtract one day from endDate if time of day is earlier than startDay
  2172. # The subtracted day will be counted by fixed units (hour and lower)
  2173. # at the end of this proc
  2174. if (endDt.hour, endDt.minute, endDt.second, endDt.nanosecond) <
  2175. (startDt.hour, startDt.minute, startDt.second, startDt.nanosecond):
  2176. if endDate.month == 1 and endDate.monthday == 1:
  2177. endDate.year.dec
  2178. endDate.monthday = 31
  2179. endDate.month = 12
  2180. elif endDate.monthday == 1:
  2181. endDate.month.dec
  2182. endDate.monthday = getDaysInMonth(endDate.month.Month, endDate.year)
  2183. else:
  2184. endDate.monthday.dec
  2185. # Years
  2186. result.years = endDate.year - startDate.year - 1
  2187. if (startDate.month, startDate.monthday) <= (endDate.month, endDate.monthday):
  2188. result.years.inc
  2189. startDate.year.inc result.years
  2190. # Months
  2191. if startDate.year < endDate.year:
  2192. result.months.inc 12 - startDate.month # Move to dec
  2193. if endDate.month != 1 or (startDate.monthday <= endDate.monthday):
  2194. result.months.inc
  2195. startDate.year = endDate.year
  2196. startDate.month = 1
  2197. else:
  2198. startDate.month = 12
  2199. if startDate.year == endDate.year:
  2200. if (startDate.monthday <= endDate.monthday):
  2201. result.months.inc endDate.month - startDate.month
  2202. startDate.month = endDate.month
  2203. elif endDate.month != 1:
  2204. let month = endDate.month - 1
  2205. let daysInMonth = getDaysInMonth(month.Month, startDate.year)
  2206. if daysInMonth < startDate.monthday:
  2207. if startDate.monthday - daysInMonth < endDate.monthday:
  2208. result.months.inc endDate.month - startDate.month - 1
  2209. startDate.month = endDate.month
  2210. startDate.monthday = startDate.monthday - daysInMonth
  2211. else:
  2212. result.months.inc endDate.month - startDate.month - 2
  2213. startDate.month = endDate.month - 2
  2214. else:
  2215. result.months.inc endDate.month - startDate.month - 1
  2216. startDate.month = endDate.month - 1
  2217. # Days
  2218. # This means that start = dec and end = jan
  2219. if startDate.year < endDate.year:
  2220. result.days.inc 31 - startDate.monthday + endDate.monthday
  2221. startDate = endDate
  2222. else:
  2223. while startDate.month < endDate.month:
  2224. let daysInMonth = getDaysInMonth(startDate.month.Month, startDate.year)
  2225. result.days.inc daysInMonth - startDate.monthday + 1
  2226. startDate.month.inc
  2227. startDate.monthday = 1
  2228. result.days.inc endDate.monthday - startDate.monthday
  2229. result.weeks = result.days div 7
  2230. result.days = result.days mod 7
  2231. startDate = endDate
  2232. # Handle hours, minutes, seconds, milliseconds, microseconds and nanoseconds
  2233. let newStartDt = dateTime(startDate.year, startDate.month.Month,
  2234. startDate.monthday, startDt.hour, startDt.minute, startDt.second,
  2235. startDt.nanosecond, startDt.timezone)
  2236. let dur = endDt - newStartDt
  2237. let parts = toParts(dur)
  2238. # There can still be a full day in `parts` since `Duration` and `TimeInterval`
  2239. # models days differently.
  2240. result.hours = parts[Hours].int + parts[Days].int * 24
  2241. result.minutes = parts[Minutes].int
  2242. result.seconds = parts[Seconds].int
  2243. result.milliseconds = parts[Milliseconds].int
  2244. result.microseconds = parts[Microseconds].int
  2245. result.nanoseconds = parts[Nanoseconds].int
  2246. proc toParts*(ti: TimeInterval): TimeIntervalParts =
  2247. ## Converts a `TimeInterval` into an array consisting of its time units,
  2248. ## starting with nanoseconds and ending with years.
  2249. ##
  2250. ## This procedure is useful for converting `TimeInterval` values to strings.
  2251. ## E.g. then you need to implement custom interval printing
  2252. runnableExamples:
  2253. var tp = toParts(initTimeInterval(years = 1, nanoseconds = 123))
  2254. doAssert tp[Years] == 1
  2255. doAssert tp[Nanoseconds] == 123
  2256. var index = 0
  2257. for name, value in fieldPairs(ti):
  2258. result[index.TimeUnit()] = value
  2259. index += 1
  2260. proc `$`*(ti: TimeInterval): string =
  2261. ## Get string representation of `TimeInterval`.
  2262. runnableExamples:
  2263. doAssert $initTimeInterval(years = 1, nanoseconds = 123) ==
  2264. "1 year and 123 nanoseconds"
  2265. doAssert $initTimeInterval() == "0 nanoseconds"
  2266. var parts: seq[string] = @[]
  2267. var tiParts = toParts(ti)
  2268. for unit in countdown(Years, Nanoseconds):
  2269. if tiParts[unit] != 0:
  2270. parts.add(stringifyUnit(tiParts[unit], unit))
  2271. result = humanizeParts(parts)
  2272. proc nanoseconds*(nanos: int): TimeInterval {.inline.} =
  2273. ## TimeInterval of `nanos` nanoseconds.
  2274. initTimeInterval(nanoseconds = nanos)
  2275. proc microseconds*(micros: int): TimeInterval {.inline.} =
  2276. ## TimeInterval of `micros` microseconds.
  2277. initTimeInterval(microseconds = micros)
  2278. proc milliseconds*(ms: int): TimeInterval {.inline.} =
  2279. ## TimeInterval of `ms` milliseconds.
  2280. initTimeInterval(milliseconds = ms)
  2281. proc seconds*(s: int): TimeInterval {.inline.} =
  2282. ## TimeInterval of `s` seconds.
  2283. ##
  2284. ## `echo getTime() + 5.seconds`
  2285. initTimeInterval(seconds = s)
  2286. proc minutes*(m: int): TimeInterval {.inline.} =
  2287. ## TimeInterval of `m` minutes.
  2288. ##
  2289. ## `echo getTime() + 5.minutes`
  2290. initTimeInterval(minutes = m)
  2291. proc hours*(h: int): TimeInterval {.inline.} =
  2292. ## TimeInterval of `h` hours.
  2293. ##
  2294. ## `echo getTime() + 2.hours`
  2295. initTimeInterval(hours = h)
  2296. proc days*(d: int): TimeInterval {.inline.} =
  2297. ## TimeInterval of `d` days.
  2298. ##
  2299. ## `echo getTime() + 2.days`
  2300. initTimeInterval(days = d)
  2301. proc weeks*(w: int): TimeInterval {.inline.} =
  2302. ## TimeInterval of `w` weeks.
  2303. ##
  2304. ## `echo getTime() + 2.weeks`
  2305. initTimeInterval(weeks = w)
  2306. proc months*(m: int): TimeInterval {.inline.} =
  2307. ## TimeInterval of `m` months.
  2308. ##
  2309. ## `echo getTime() + 2.months`
  2310. initTimeInterval(months = m)
  2311. proc years*(y: int): TimeInterval {.inline.} =
  2312. ## TimeInterval of `y` years.
  2313. ##
  2314. ## `echo getTime() + 2.years`
  2315. initTimeInterval(years = y)
  2316. proc evaluateInterval(dt: DateTime, interval: TimeInterval):
  2317. tuple[adjDur, absDur: Duration] =
  2318. ## Evaluates how many nanoseconds the interval is worth
  2319. ## in the context of `dt`.
  2320. ## The result in split into an adjusted diff and an absolute diff.
  2321. var months = interval.years * 12 + interval.months
  2322. var curYear = dt.year
  2323. var curMonth = dt.month
  2324. result = default(tuple[adjDur, absDur: Duration])
  2325. # Subtracting
  2326. if months < 0:
  2327. for mth in countdown(-1 * months, 1):
  2328. if curMonth == mJan:
  2329. curMonth = mDec
  2330. curYear.dec
  2331. else:
  2332. curMonth.dec()
  2333. let days = getDaysInMonth(curMonth, curYear)
  2334. result.adjDur = result.adjDur - initDuration(days = days)
  2335. # Adding
  2336. else:
  2337. for mth in 1 .. months:
  2338. let days = getDaysInMonth(curMonth, curYear)
  2339. result.adjDur = result.adjDur + initDuration(days = days)
  2340. if curMonth == mDec:
  2341. curMonth = mJan
  2342. curYear.inc
  2343. else:
  2344. curMonth.inc()
  2345. result.adjDur = result.adjDur + initDuration(
  2346. days = interval.days,
  2347. weeks = interval.weeks)
  2348. result.absDur = initDuration(
  2349. nanoseconds = interval.nanoseconds,
  2350. microseconds = interval.microseconds,
  2351. milliseconds = interval.milliseconds,
  2352. seconds = interval.seconds,
  2353. minutes = interval.minutes,
  2354. hours = interval.hours)
  2355. proc `+`*(dt: DateTime, interval: TimeInterval): DateTime =
  2356. ## Adds `interval` to `dt`. Components from `interval` are added
  2357. ## in the order of their size, i.e. first the `years` component, then the
  2358. ## `months` component and so on. The returned `DateTime` will have the
  2359. ## same timezone as the input.
  2360. ##
  2361. ## Note that when adding months, monthday overflow is allowed. This means that
  2362. ## if the resulting month doesn't have enough days it, the month will be
  2363. ## incremented and the monthday will be set to the number of days overflowed.
  2364. ## So adding one month to `31 October` will result in `31 November`, which
  2365. ## will overflow and result in `1 December`.
  2366. runnableExamples:
  2367. let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
  2368. doAssert $(dt + 1.months) == "2017-04-30T00:00:00Z"
  2369. # This is correct and happens due to monthday overflow.
  2370. doAssert $(dt - 1.months) == "2017-03-02T00:00:00Z"
  2371. let (adjDur, absDur) = evaluateInterval(dt, interval)
  2372. if adjDur != DurationZero:
  2373. var zt = dt.timezone.zonedTimeFromAdjTime(dt.toAdjTime + adjDur)
  2374. if absDur != DurationZero:
  2375. zt = dt.timezone.zonedTimeFromTime(zt.time + absDur)
  2376. result = initDateTime(zt, dt.timezone)
  2377. else:
  2378. result = initDateTime(zt, dt.timezone)
  2379. else:
  2380. var zt = dt.timezone.zonedTimeFromTime(dt.toTime + absDur)
  2381. result = initDateTime(zt, dt.timezone)
  2382. proc `-`*(dt: DateTime, interval: TimeInterval): DateTime =
  2383. ## Subtract `interval` from `dt`. Components from `interval` are
  2384. ## subtracted in the order of their size, i.e. first the `years` component,
  2385. ## then the `months` component and so on. The returned `DateTime` will
  2386. ## have the same timezone as the input.
  2387. runnableExamples:
  2388. let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
  2389. doAssert $(dt - 5.days) == "2017-03-25T00:00:00Z"
  2390. dt + (-interval)
  2391. proc `+`*(time: Time, interval: TimeInterval): Time =
  2392. ## Adds `interval` to `time`.
  2393. ## If `interval` contains any years, months, weeks or days the operation
  2394. ## is performed in the local timezone.
  2395. runnableExamples:
  2396. let tm = fromUnix(0)
  2397. doAssert tm + 5.seconds == fromUnix(5)
  2398. if interval.isStaticInterval:
  2399. time + evaluateStaticInterval(interval)
  2400. else:
  2401. toTime(time.local + interval)
  2402. proc `-`*(time: Time, interval: TimeInterval): Time =
  2403. ## Subtracts `interval` from Time `time`.
  2404. ## If `interval` contains any years, months, weeks or days the operation
  2405. ## is performed in the local timezone.
  2406. runnableExamples:
  2407. let tm = fromUnix(5)
  2408. doAssert tm - 5.seconds == fromUnix(0)
  2409. if interval.isStaticInterval:
  2410. time - evaluateStaticInterval(interval)
  2411. else:
  2412. toTime(time.local - interval)
  2413. proc `+=`*(a: var DateTime, b: TimeInterval) =
  2414. a = a + b
  2415. proc `-=`*(a: var DateTime, b: TimeInterval) =
  2416. a = a - b
  2417. proc `+=`*(t: var Time, b: TimeInterval) =
  2418. t = t + b
  2419. proc `-=`*(t: var Time, b: TimeInterval) =
  2420. t = t - b
  2421. #
  2422. # Iso week
  2423. #
  2424. proc initDateTime*(weekday: WeekDay, isoweek: IsoWeekRange, isoyear: IsoYear,
  2425. hour: HourRange, minute: MinuteRange, second: SecondRange,
  2426. nanosecond: NanosecondRange,
  2427. zone: Timezone = local()): DateTime {.raises: [], tags: [], since: (1, 5).} =
  2428. ## Create a new `DateTime <#DateTime>`_ from a weekday and an ISO 8601 week number and year
  2429. ## in the specified timezone.
  2430. ##
  2431. ## .. warning:: The ISO week-based year can correspond to the following or previous year from 29 December to January 3.
  2432. runnableExamples:
  2433. assert initDateTime(21, mApr, 2018, 00, 00, 00) == initDateTime(dSat, 16, 2018.IsoYear, 00, 00, 00)
  2434. assert initDateTime(30, mDec, 2019, 00, 00, 00) == initDateTime(dMon, 01, 2020.IsoYear, 00, 00, 00)
  2435. assert initDateTime(13, mSep, 2020, 00, 00, 00) == initDateTime(dSun, 37, 2020.IsoYear, 00, 00, 00)
  2436. assert initDateTime(2, mJan, 2021, 00, 00, 00) == initDateTime(dSat, 53, 2020.IsoYear, 00, 00, 00)
  2437. # source https://webspace.science.uu.nl/~gent0113/calendar/isocalendar.htm
  2438. let d = isoweek * 7 + weekday.int - initDateTime(4, mJan, isoyear.int, 00, 00, 00, zone).weekday.int - 4
  2439. initDateTime(1, mJan, isoyear.int, hour, minute, second, nanosecond, zone) + initTimeInterval(days=d)
  2440. proc initDateTime*(weekday: WeekDay, isoweek: IsoWeekRange, isoyear: IsoYear,
  2441. hour: HourRange, minute: MinuteRange, second: SecondRange,
  2442. zone: Timezone = local()): DateTime {.raises: [], tags: [], since: (1, 5).} =
  2443. initDateTime(weekday, isoweek, isoyear, hour, minute, second, 0, zone)
  2444. #
  2445. # Other
  2446. #
  2447. proc epochTime*(): float {.tags: [TimeEffect].} =
  2448. ## Gets time after the UNIX epoch (1970) in seconds. It is a float
  2449. ## because sub-second resolution is likely to be supported (depending
  2450. ## on the hardware/OS).
  2451. ##
  2452. ## `getTime` should generally be preferred over this proc.
  2453. ##
  2454. ## .. warning:: Unsuitable for benchmarking (but still better than `now`),
  2455. ## use `monotimes.getMonoTime` or `cpuTime` instead, depending on the use case.
  2456. when defined(macosx):
  2457. var a {.noinit.}: Timeval
  2458. gettimeofday(a)
  2459. result = toBiggestFloat(a.tv_sec.int64) + toBiggestFloat(
  2460. a.tv_usec)*0.00_0001
  2461. elif defined(posix):
  2462. var ts {.noinit.}: Timespec
  2463. discard clock_gettime(CLOCK_REALTIME, ts)
  2464. result = toBiggestFloat(ts.tv_sec.int64) +
  2465. toBiggestFloat(ts.tv_nsec.int64) / 1_000_000_000
  2466. elif defined(windows):
  2467. var f {.noinit.}: winlean.FILETIME
  2468. getSystemTimeAsFileTime(f)
  2469. var i64 = rdFileTime(f) - epochDiff
  2470. var secs = i64 div rateDiff
  2471. var subsecs = i64 mod rateDiff
  2472. result = toFloat(int(secs)) + toFloat(int(subsecs)) * 0.0000001
  2473. elif defined(js):
  2474. result = newDate().getTime() / 1000
  2475. else:
  2476. {.error: "unknown OS".}
  2477. when not defined(js):
  2478. type
  2479. Clock {.importc: "clock_t".} = distinct int
  2480. proc getClock(): Clock
  2481. {.importc: "clock", header: "<time.h>", tags: [TimeEffect], used, sideEffect.}
  2482. var
  2483. clocksPerSec {.importc: "CLOCKS_PER_SEC", nodecl, used.}: int
  2484. proc cpuTime*(): float {.tags: [TimeEffect].} =
  2485. ## Gets time spent that the CPU spent to run the current process in
  2486. ## seconds. This may be more useful for benchmarking than `epochTime`.
  2487. ## However, it may measure the real time instead (depending on the OS).
  2488. ## The value of the result has no meaning.
  2489. ## To generate useful timing values, take the difference between
  2490. ## the results of two `cpuTime` calls:
  2491. runnableExamples:
  2492. var t0 = cpuTime()
  2493. # some useless work here (calculate fibonacci)
  2494. var fib = @[0, 1, 1]
  2495. for i in 1..10:
  2496. fib.add(fib[^1] + fib[^2])
  2497. echo "CPU time [s] ", cpuTime() - t0
  2498. echo "Fib is [s] ", fib
  2499. ## When the flag `--benchmarkVM` is passed to the compiler, this proc is
  2500. ## also available at compile time
  2501. when defined(posix) and not defined(osx) and declared(CLOCK_THREAD_CPUTIME_ID):
  2502. # 'clocksPerSec' is a compile-time constant, possibly a
  2503. # rather awful one, so use clock_gettime instead
  2504. var ts: Timespec
  2505. discard clock_gettime(CLOCK_THREAD_CPUTIME_ID, ts)
  2506. result = toFloat(ts.tv_sec.int) +
  2507. toFloat(ts.tv_nsec.int) / 1_000_000_000
  2508. else:
  2509. result = toFloat(int(getClock())) / toFloat(clocksPerSec)
  2510. #
  2511. # Deprecations
  2512. #
  2513. proc `nanosecond=`*(dt: var DateTime, value: NanosecondRange) {.deprecated: "Deprecated since v1.3.1".} =
  2514. dt.nanosecond = value
  2515. proc `second=`*(dt: var DateTime, value: SecondRange) {.deprecated: "Deprecated since v1.3.1".} =
  2516. dt.second = value
  2517. proc `minute=`*(dt: var DateTime, value: MinuteRange) {.deprecated: "Deprecated since v1.3.1".} =
  2518. dt.minute = value
  2519. proc `hour=`*(dt: var DateTime, value: HourRange) {.deprecated: "Deprecated since v1.3.1".} =
  2520. dt.hour = value
  2521. proc `monthdayZero=`*(dt: var DateTime, value: int) {.deprecated: "Deprecated since v1.3.1".} =
  2522. dt.monthdayZero = value
  2523. proc `monthZero=`*(dt: var DateTime, value: int) {.deprecated: "Deprecated since v1.3.1".} =
  2524. dt.monthZero = value
  2525. proc `year=`*(dt: var DateTime, value: int) {.deprecated: "Deprecated since v1.3.1".} =
  2526. dt.year = value
  2527. proc `weekday=`*(dt: var DateTime, value: WeekDay) {.deprecated: "Deprecated since v1.3.1".} =
  2528. dt.weekday = value
  2529. proc `yearday=`*(dt: var DateTime, value: YeardayRange) {.deprecated: "Deprecated since v1.3.1".} =
  2530. dt.yearday = value
  2531. proc `isDst=`*(dt: var DateTime, value: bool) {.deprecated: "Deprecated since v1.3.1".} =
  2532. dt.isDst = value
  2533. proc `timezone=`*(dt: var DateTime, value: Timezone) {.deprecated: "Deprecated since v1.3.1".} =
  2534. dt.timezone = value
  2535. proc `utcOffset=`*(dt: var DateTime, value: int) {.deprecated: "Deprecated since v1.3.1".} =
  2536. dt.utcOffset = value