times.nim 95 KB

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