times.nim 104 KB

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