times.nim 102 KB

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