times.nim 104 KB

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