times.nim 103 KB

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