times.nim 96 KB

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