times.nim 100 KB

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