times.nim 104 KB

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