-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
times.nim
2755 lines (2445 loc) · 101 KB
/
times.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
#
# Nim's Runtime Library
# (c) Copyright 2018 Nim contributors
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
##[
The ``times`` module contains routines and types for dealing with time using
the `proleptic Gregorian calendar<https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar>`_.
It's also available for the
`JavaScript target <backends.html#backends-the-javascript-target>`_.
Although the ``times`` module support nanosecond time resolution, the
resolution used by ``getTime()`` depends on the platform and backend
(JS is limited to millisecond precision).
Examples
========
.. code-block:: nim
import times, os
# Simple benchmarking
let time = cpuTime()
sleep(100) # Replace this with something to be timed
echo "Time taken: ", cpuTime() - time
# Current date & time
let now1 = now() # Current timestamp as a DateTime in local time
let now2 = now().utc # Current timestamp as a DateTime in UTC
let now3 = getTime() # Current timestamp as a Time
# Arithmetic using Duration
echo "One hour from now : ", now() + initDuration(hours = 1)
# Arithmetic using TimeInterval
echo "One year from now : ", now() + 1.years
echo "One month from now : ", now() + 1.months
Parsing and Formatting Dates
============================
The ``DateTime`` type can be parsed and formatted using the different
``parse`` and ``format`` procedures.
.. code-block:: nim
let dt = parse("2000-01-01", "yyyy-MM-dd")
echo dt.format("yyyy-MM-dd")
The different format patterns that are supported are documented below.
============= ================================================================================= ================================================
Pattern Description Example
============= ================================================================================= ================================================
``d`` Numeric value representing the day of the month, | ``1/04/2012 -> 1``
it will be either one or two digits long. | ``21/04/2012 -> 21``
``dd`` Same as above, but is always two digits. | ``1/04/2012 -> 01``
| ``21/04/2012 -> 21``
``ddd`` Three letter string which indicates the day of the week. | ``Saturday -> Sat``
| ``Monday -> Mon``
``dddd`` Full string for the day of the week. | ``Saturday -> Saturday``
| ``Monday -> Monday``
``h`` The hours in one digit if possible. Ranging from 1-12. | ``5pm -> 5``
| ``2am -> 2``
``hh`` The hours in two digits always. If the hour is one digit 0 is prepended. | ``5pm -> 05``
| ``11am -> 11``
``H`` The hours in one digit if possible, ranging from 0-23. | ``5pm -> 17``
| ``2am -> 2``
``HH`` The hours in two digits always. 0 is prepended if the hour is one digit. | ``5pm -> 17``
| ``2am -> 02``
``m`` The minutes in 1 digit if possible. | ``5:30 -> 30``
| ``2:01 -> 1``
``mm`` Same as above but always 2 digits, 0 is prepended if the minute is one digit. | ``5:30 -> 30``
| ``2:01 -> 01``
``M`` The month in one digit if possible. | ``September -> 9``
| ``December -> 12``
``MM`` The month in two digits always. 0 is prepended. | ``September -> 09``
| ``December -> 12``
``MMM`` Abbreviated three-letter form of the month. | ``September -> Sep``
| ``December -> Dec``
``MMMM`` Full month string, properly capitalized. | ``September -> September``
``s`` Seconds as one digit if possible. | ``00:00:06 -> 6``
``ss`` Same as above but always two digits. 0 is prepended. | ``00:00:06 -> 06``
``t`` ``A`` when time is in the AM. ``P`` when time is in the PM. | ``5pm -> P``
| ``2am -> A``
``tt`` Same as above, but ``AM`` and ``PM`` instead of ``A`` and ``P`` respectively. | ``5pm -> PM``
| ``2am -> AM``
``yy`` The last two digits of the year. When parsing, the current century is assumed. | ``2012 AD -> 12``
``yyyy`` The year, padded to atleast four digits. | ``2012 AD -> 2012``
Is always positive, even when the year is BC. | ``24 AD -> 0024``
When the year is more than four digits, '+' is prepended. | ``24 BC -> 00024``
| ``12345 AD -> +12345``
``YYYY`` The year without any padding. | ``2012 AD -> 2012``
Is always positive, even when the year is BC. | ``24 AD -> 24``
| ``24 BC -> 24``
| ``12345 AD -> 12345``
``uuuu`` The year, padded to atleast four digits. Will be negative when the year is BC. | ``2012 AD -> 2012``
When the year is more than four digits, '+' is prepended unless the year is BC. | ``24 AD -> 0024``
| ``24 BC -> -0023``
| ``12345 AD -> +12345``
``UUUU`` The year without any padding. Will be negative when the year is BC. | ``2012 AD -> 2012``
| ``24 AD -> 24``
| ``24 BC -> -23``
| ``12345 AD -> 12345``
``z`` Displays the timezone offset from UTC. | ``UTC+7 -> +7``
| ``UTC-5 -> -5``
``zz`` Same as above but with leading 0. | ``UTC+7 -> +07``
| ``UTC-5 -> -05``
``zzz`` Same as above but with ``:mm`` where *mm* represents minutes. | ``UTC+7 -> +07:00``
| ``UTC-5 -> -05:00``
``zzzz`` Same as above but with ``:ss`` where *ss* represents seconds. | ``UTC+7 -> +07:00:00``
| ``UTC-5 -> -05:00:00``
``g`` Era: AD or BC | ``300 AD -> AD``
| ``300 BC -> BC``
``fff`` Milliseconds display | ``1000000 nanoseconds -> 1``
``ffffff`` Microseconds display | ``1000000 nanoseconds -> 1000``
``fffffffff`` Nanoseconds display | ``1000000 nanoseconds -> 1000000``
============= ================================================================================= ================================================
Other strings can be inserted by putting them in ``''``. For example
``hh'->'mm`` will give ``01->56``. The following characters can be
inserted without quoting them: ``:`` ``-`` ``(`` ``)`` ``/`` ``[`` ``]``
``,``. A literal ``'`` can be specified with ``''``.
However you don't need to necessarily separate format patterns, an
unambiguous format string like ``yyyyMMddhhmmss`` is valid too (although
only for years in the range 1..9999).
Duration vs TimeInterval
============================
The ``times`` module exports two similiar types that are both used to
represent some amount of time: `Duration <#Duration>`_ and
`TimeInterval <#TimeInterval>`_.
This section explains how they differ and when one should be prefered over the
other (short answer: use ``Duration`` unless support for months and years is
needed).
Duration
----------------------------
A ``Duration`` represents a duration of time stored as seconds and
nanoseconds. A ``Duration`` is always fully normalized, so
``initDuration(hours = 1)`` and ``initDuration(minutes = 60)`` are equivilant.
Arithmetics with a ``Duration`` is very fast, especially when used with the
``Time`` type, since it only involves basic arithmetic. Because ``Duration``
is more performant and easier to understand it should generally prefered.
TimeInterval
----------------------------
A ``TimeInterval`` represents some amount of time expressed in calendar
units, for example "1 year and 2 days". Since some units cannot be
normalized (the length of a year is different for leap years for example),
the ``TimeInterval`` type uses seperate fields for every unit. The
``TimeInterval``'s returned form the this module generally don't normalize
**anything**, so even units that could be normalized (like seconds,
milliseconds and so on) are left untouched.
Arithmetics with a ``TimeInterval`` can be very slow, because it requires
timezone information.
Since it's slower and more complex, the ``TimeInterval`` type should be
avoided unless the program explicitly needs the features it offers that
``Duration`` doesn't have.
How long is a day?
----------------------------
It should be especially noted that the handling of days differs between
``TimeInterval`` and ``Duration``. The ``Duration`` type always treats a day
as exactly 86400 seconds. For ``TimeInterval``, it's more complex.
As an example, consider the amount of time between these two timestamps, both
in the same timezone:
- 2018-03-25T12:00+02:00
- 2018-03-26T12:00+01:00
If only the date & time is considered, it appears that exatly one day has
passed. However, the UTC offsets are different, which means that the
UTC offset was changed somewhere between. This happens twice each year for
timezones that use daylight savings time. Because of this change, the amount
of time that has passed is actually 25 hours.
The ``TimeInterval`` type uses calendar units, and will say that exactly one
day has passed. The ``Duration`` type on the other hand normalizes everything
to seconds, and will therefore say that 90000 seconds has passed, which is
the same as 25 hours.
]##
import strutils, math, options
include "system/inclrtl"
when defined(JS):
import jscore
# This is really bad, but overflow checks are broken badly for
# ints on the JS backend. See #6752.
{.push overflowChecks: off.}
proc `*`(a, b: int64): int64 =
system.`*`(a, b)
proc `*`(a, b: int): int =
system.`*`(a, b)
proc `+`(a, b: int64): int64 =
system.`+`(a, b)
proc `+`(a, b: int): int =
system.`+`(a, b)
proc `-`(a, b: int64): int64 =
system.`-`(a, b)
proc `-`(a, b: int): int =
system.`-`(a, b)
proc inc(a: var int, b: int) =
system.inc(a, b)
proc inc(a: var int64, b: int) =
system.inc(a, b)
{.pop.}
elif defined(posix):
import posix
type CTime = posix.Time
var
realTimeClockId {.importc: "CLOCK_REALTIME", header: "<time.h>".}: Clockid
cpuClockId
{.importc: "CLOCK_THREAD_CPUTIME_ID", header: "<time.h>".}: Clockid
when not defined(freebsd) and not defined(netbsd) and not defined(openbsd):
var timezone {.importc, header: "<time.h>".}: int
when not defined(valgrind_workaround_10121):
tzset()
when defined(macosx):
proc gettimeofday(tp: var Timeval, unused: pointer = nil)
{.importc: "gettimeofday", header: "<sys/time.h>".}
elif defined(windows):
import winlean, std/time_t
type CTime = time_t.Time
# visual c's c runtime exposes these under a different name
var timezone {.importc: "_timezone", header: "<time.h>".}: int
type
Tm {.importc: "struct tm", header: "<time.h>", final, pure.} = object
tm_sec*: cint ## Seconds [0,60].
tm_min*: cint ## Minutes [0,59].
tm_hour*: cint ## Hour [0,23].
tm_mday*: cint ## Day of month [1,31].
tm_mon*: cint ## Month of year [0,11].
tm_year*: cint ## Years since 1900.
tm_wday*: cint ## Day of week [0,6] (Sunday =0).
tm_yday*: cint ## Day of year [0,365].
tm_isdst*: cint ## Daylight Savings flag.
proc localtime(a1: var CTime): ptr Tm {.importc, header: "<time.h>".}
type
Month* = enum ## Represents a month. Note that the enum starts at ``1``,
## so ``ord(month)`` will give the month number in the
## range ``1..12``.
mJan = (1, "January")
mFeb = "February"
mMar = "March"
mApr = "April"
mMay = "May"
mJun = "June"
mJul = "July"
mAug = "August"
mSep = "September"
mOct = "October"
mNov = "November"
mDec = "December"
WeekDay* = enum ## Represents a weekday.
dMon = "Monday"
dTue = "Tuesday"
dWed = "Wednesday"
dThu = "Thursday"
dFri = "Friday"
dSat = "Saturday"
dSun = "Sunday"
DateTimeLocale* = object
MMM*: array[mJan..mDec, string]
MMMM*: array[mJan..mDec, string]
ddd*: array[dMon..dSun, string]
dddd*: array[dMon..dSun, string]
MonthdayRange* = range[1..31]
HourRange* = range[0..23]
MinuteRange* = range[0..59]
SecondRange* = range[0..60]
YeardayRange* = range[0..365]
NanosecondRange* = range[0..999_999_999]
Time* = object ## Represents a point in time.
seconds: int64
nanosecond: NanosecondRange
DateTime* = object of RootObj ## \
## Represents a time in different parts. Although this type can represent
## leap seconds, they are generally not supported in this module. They are
## not ignored, but the ``DateTime``'s returned by procedures in this
## module will never have a leap second.
##
## **Warning**: even though the fields of ``DateTime`` are exported,
## they should never be mutated directly. Doing so is unsafe and will
## result in the ``DateTime`` ending up in an invalid state.
##
## Instead of mutating the fields directly, use the `Duration <#Duration>`_
## and `TimeInterval <#TimeInterval>`_ types for arithmetic and use the
## `initDateTime proc <#initDateTime,MonthdayRange,Month,int,HourRange,MinuteRange,SecondRange,NanosecondRange,Timezone>`_
## for changing a specific field.
nanosecond*: NanosecondRange ## The number of nanoseconds after the second,
## in the range 0 to 999_999_999.
second*: SecondRange ## The number of seconds after the minute,
## normally in the range 0 to 59, but can
## be up to 60 to allow for a leap second.
minute*: MinuteRange ## The number of minutes after the hour,
## in the range 0 to 59.
hour*: HourRange ## The number of hours past midnight,
## in the range 0 to 23.
monthday*: MonthdayRange ## The day of the month, in the range 1 to 31.
month*: Month ## The month.
year*: int ## The year, using astronomical year numbering
## (meaning that before year 1 is year 0,
## then year -1 and so on).
weekday*: WeekDay ## The day of the week.
yearday*: YeardayRange ## The number of days since January 1,
## in the range 0 to 365.
isDst*: bool ## Determines whether DST is in effect.
## Always false for the JavaScript backend.
timezone*: Timezone ## The timezone represented as an implementation
## of ``Timezone``.
utcOffset*: int ## The offset in seconds west of UTC, including
## any offset due to DST. Note that the sign of
## this number is the opposite of the one in a
## formatted offset string like ``+01:00`` (which
## would be equivalent to the UTC offset
## ``-3600``).
Duration* = object ## Represents a fixed duration of time, meaning a duration
## that has constant length independent of the context.
##
## To create a new ``Duration``, use `initDuration proc
## <#initDuration,int64,int64,int64,int64,int64,int64,int64,int64>`_.
seconds: int64
nanosecond: NanosecondRange
TimeUnit* = enum ## Different units of time.
Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes, Hours, Days,
Weeks, Months, Years
FixedTimeUnit* = range[Nanoseconds..Weeks] ## \
## Subrange of ``TimeUnit`` that only includes units of fixed duration.
## These are the units that can be represented by a ``Duration``.
TimeInterval* = object ## \
## Represents a non-fixed duration of time. Can be used to add and
## subtract non-fixed time units from a `DateTime <#DateTime>`_ or
## `Time <#Time>`_.
##
## Create a new ``TimeInterval`` with `initTimeInterval proc
## <#initTimeInterval,int,int,int,int,int,int,int,int,int,int>`_.
##
## Note that ``TimeInterval`` doesn't represent a fixed duration of time,
## since the duration of some units depend on the context (e.g a year
## can be either 365 or 366 days long). The non-fixed time units are
## years, months, days and week.
##
## Note that ``TimeInterval``'s returned from the ``times`` module are
## never normalized. If you want to normalize a time unit,
## `Duration <#Duration>`_ should be used instead.
nanoseconds*: int ## The number of nanoseconds
microseconds*: int ## The number of microseconds
milliseconds*: int ## The number of milliseconds
seconds*: int ## The number of seconds
minutes*: int ## The number of minutes
hours*: int ## The number of hours
days*: int ## The number of days
weeks*: int ## The number of weeks
months*: int ## The number of months
years*: int ## The number of years
Timezone* = ref object ## \
## Timezone interface for supporting `DateTime <#DateTime>`_\s of arbritary
## timezones. The ``times`` module only supplies implementations for the
## systems local time and UTC.
zonedTimeFromTimeImpl: proc (x: Time): ZonedTime
{.tags: [], raises: [], benign.}
zonedTimeFromAdjTimeImpl: proc (x: Time): ZonedTime
{.tags: [], raises: [], benign.}
name: string
ZonedTime* = object ## Represents a point in time with an associated
## UTC offset and DST flag. This type is only used for
## implementing timezones.
time*: Time ## The point in time being represented.
utcOffset*: int ## The offset in seconds west of UTC,
## including any offset due to DST.
isDst*: bool ## Determines whether DST is in effect.
DurationParts* = array[FixedTimeUnit, int64] # Array of Duration parts starts
TimeIntervalParts* = array[TimeUnit, int] # Array of Duration parts starts
TimesMutableTypes = DateTime | Time | Duration | TimeInterval
const
secondsInMin = 60
secondsInHour = 60*60
secondsInDay = 60*60*24
rateDiff = 10000000'i64 # 100 nsecs
# The number of hectonanoseconds between 1601/01/01 (windows epoch)
# and 1970/01/01 (unix epoch).
epochDiff = 116444736000000000'i64
const unitWeights: array[FixedTimeUnit, int64] = [
1'i64,
1000,
1_000_000,
1e9.int64,
secondsInMin * 1e9.int64,
secondsInHour * 1e9.int64,
secondsInDay * 1e9.int64,
7 * secondsInDay * 1e9.int64,
]
const DefaultLocale* = DateTimeLocale(
MMM: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
MMMM: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
ddd: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
dddd: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
)
proc convert*[T: SomeInteger](unitFrom, unitTo: FixedTimeUnit, quantity: T): T
{.inline.} =
## Convert a quantity of some duration unit to another duration unit.
## This proc only deals with integers, so the result might be truncated.
runnableExamples:
doAssert convert(Days, Hours, 2) == 48
doAssert convert(Days, Weeks, 13) == 1 # Truncated
doAssert convert(Seconds, Milliseconds, -1) == -1000
if unitFrom < unitTo:
(quantity div (unitWeights[unitTo] div unitWeights[unitFrom])).T
else:
((unitWeights[unitFrom] div unitWeights[unitTo]) * quantity).T
proc normalize[T: Duration|Time](seconds, nanoseconds: int64): T =
## Normalize a (seconds, nanoseconds) pair and return it as either
## a ``Duration`` or ``Time``. A normalized ``Duration|Time`` has a
## positive nanosecond part in the range ``NanosecondRange``.
result.seconds = seconds + convert(Nanoseconds, Seconds, nanoseconds)
var nanosecond = nanoseconds mod convert(Seconds, Nanoseconds, 1)
if nanosecond < 0:
nanosecond += convert(Seconds, Nanoseconds, 1)
result.seconds -= 1
result.nanosecond = nanosecond.int
# Forward declarations
proc utcTzInfo(time: Time): ZonedTime
{.tags: [], raises: [], benign.}
proc localZonedTimeFromTime(time: Time): ZonedTime
{.tags: [], raises: [], benign.}
proc localZonedTimeFromAdjTime(adjTime: Time): ZonedTime
{.tags: [], raises: [], benign.}
proc initTime*(unix: int64, nanosecond: NanosecondRange): Time
{.tags: [], raises: [], benign, noSideEffect.}
proc nanosecond*(time: Time): NanosecondRange =
## Get the fractional part of a ``Time`` as the number
## of nanoseconds of the second.
time.nanosecond
proc initDuration*(nanoseconds, microseconds, milliseconds,
seconds, minutes, hours, days, weeks: int64 = 0): Duration =
## Create a new `Duration <#Duration>`_.
runnableExamples:
let dur = initDuration(seconds = 1, milliseconds = 1)
doAssert dur.milliseconds == 1
doAssert dur.seconds == 1
let seconds = convert(Weeks, Seconds, weeks) +
convert(Days, Seconds, days) +
convert(Minutes, Seconds, minutes) +
convert(Hours, Seconds, hours) +
convert(Seconds, Seconds, seconds) +
convert(Milliseconds, Seconds, milliseconds) +
convert(Microseconds, Seconds, microseconds) +
convert(Nanoseconds, Seconds, nanoseconds)
let nanoseconds = (convert(Milliseconds, Nanoseconds, milliseconds mod 1000) +
convert(Microseconds, Nanoseconds, microseconds mod 1_000_000) +
nanoseconds mod 1_000_000_000).int
# Nanoseconds might be negative so we must normalize.
result = normalize[Duration](seconds, nanoseconds)
template convert(dur: Duration, unit: static[FixedTimeUnit]): int64 =
# The correction is required due to how durations are normalized.
# For example,` initDuration(nanoseconds = -1)` is stored as
# { seconds = -1, nanoseconds = 999999999 }.
let correction = dur.seconds < 0 and dur.nanosecond > 0
when unit >= Seconds:
convert(Seconds, unit, dur.seconds + ord(correction))
else:
if correction:
convert(Seconds, unit, dur.seconds + 1) -
convert(Nanoseconds, unit,
convert(Seconds, Nanoseconds, 1) - dur.nanosecond)
else:
convert(Seconds, unit, dur.seconds) +
convert(Nanoseconds, unit, dur.nanosecond)
proc inWeeks*(dur: Duration): int64 =
## Convert the duration to the number of whole weeks.
runnableExamples:
let dur = initDuration(days = 8)
doAssert dur.inWeeks == 1
dur.convert(Weeks)
proc inDays*(dur: Duration): int64 =
## Convert the duration to the number of whole days.
runnableExamples:
let dur = initDuration(hours = -50)
doAssert dur.inDays == -2
dur.convert(Days)
proc inHours*(dur: Duration): int64 =
## Convert the duration to the number of whole hours.
runnableExamples:
let dur = initDuration(minutes = 60, days = 2)
doAssert dur.inHours == 49
dur.convert(Hours)
proc inMinutes*(dur: Duration): int64 =
## Convert the duration to the number of whole minutes.
runnableExamples:
let dur = initDuration(hours = 2, seconds = 10)
doAssert dur.inMinutes == 120
dur.convert(Minutes)
proc inSeconds*(dur: Duration): int64 =
## Convert the duration to the number of whole seconds.
runnableExamples:
let dur = initDuration(hours = 2, milliseconds = 10)
doAssert dur.inSeconds == 2 * 60 * 60
dur.convert(Seconds)
proc inMilliseconds*(dur: Duration): int64 =
## Convert the duration to the number of whole milliseconds.
runnableExamples:
let dur = initDuration(seconds = -2)
doAssert dur.inMilliseconds == -2000
dur.convert(Milliseconds)
proc inMicroseconds*(dur: Duration): int64 =
## Convert the duration to the number of whole microseconds.
runnableExamples:
let dur = initDuration(seconds = -2)
doAssert dur.inMicroseconds == -2000000
dur.convert(Microseconds)
proc inNanoseconds*(dur: Duration): int64 =
## Convert the duration to the number of whole nanoseconds.
runnableExamples:
let dur = initDuration(seconds = -2)
doAssert dur.inNanoseconds == -2000000000
dur.convert(Nanoseconds)
proc fromUnix*(unix: int64): Time
{.benign, tags: [], raises: [], noSideEffect.} =
## Convert a unix timestamp (seconds since ``1970-01-01T00:00:00Z``)
## to a ``Time``.
runnableExamples:
doAssert $fromUnix(0).utc == "1970-01-01T00:00:00Z"
initTime(unix, 0)
proc toUnix*(t: Time): int64 {.benign, tags: [], raises: [], noSideEffect.} =
## Convert ``t`` to a unix timestamp (seconds since ``1970-01-01T00:00:00Z``).
runnableExamples:
doAssert fromUnix(0).toUnix() == 0
t.seconds
proc fromWinTime*(win: int64): Time =
## Convert a Windows file time (100-nanosecond intervals since
## ``1601-01-01T00:00:00Z``) to a ``Time``.
const hnsecsPerSec = convert(Seconds, Nanoseconds, 1) div 100
let nanos = floorMod(win, hnsecsPerSec) * 100
let seconds = floorDiv(win - epochDiff, hnsecsPerSec)
result = initTime(seconds, nanos)
proc toWinTime*(t: Time): int64 =
## Convert ``t`` to a Windows file time (100-nanosecond intervals
## since ``1601-01-01T00:00:00Z``).
result = t.seconds * rateDiff + epochDiff + t.nanosecond div 100
proc isLeapYear*(year: int): bool =
## Returns true if ``year`` is a leap year.
runnableExamples:
doAssert isLeapYear(2000)
doAssert not isLeapYear(1900)
year mod 4 == 0 and (year mod 100 != 0 or year mod 400 == 0)
proc getDaysInMonth*(month: Month, year: int): int =
## Get the number of days in ``month`` of ``year``.
# http://www.dispersiondesign.com/articles/time/number_of_days_in_a_month
runnableExamples:
doAssert getDaysInMonth(mFeb, 2000) == 29
doAssert getDaysInMonth(mFeb, 2001) == 28
case month
of mFeb: result = if isLeapYear(year): 29 else: 28
of mApr, mJun, mSep, mNov: result = 30
else: result = 31
proc getDaysInYear*(year: int): int =
## Get the number of days in a ``year``
runnableExamples:
doAssert getDaysInYear(2000) == 366
doAssert getDaysInYear(2001) == 365
result = 365 + (if isLeapYear(year): 1 else: 0)
proc assertValidDate(monthday: MonthdayRange, month: Month, year: int)
{.inline.} =
assert monthday <= getDaysInMonth(month, year),
$year & "-" & intToStr(ord(month), 2) & "-" & $monthday &
" is not a valid date"
proc toEpochDay(monthday: MonthdayRange, month: Month, year: int): int64 =
## Get the epoch day from a year/month/day date.
## The epoch day is the number of days since 1970/01/01
## (it might be negative).
# Based on http://howardhinnant.github.io/date_algorithms.html
assertValidDate monthday, month, year
var (y, m, d) = (year, ord(month), monthday.int)
if m <= 2:
y.dec
let era = (if y >= 0: y else: y-399) div 400
let yoe = y - era * 400
let doy = (153 * (m + (if m > 2: -3 else: 9)) + 2) div 5 + d-1
let doe = yoe * 365 + yoe div 4 - yoe div 100 + doy
return era * 146097 + doe - 719468
proc fromEpochDay(epochday: int64):
tuple[monthday: MonthdayRange, month: Month, year: int] =
## Get the year/month/day date from a epoch day.
## The epoch day is the number of days since 1970/01/01
## (it might be negative).
# Based on http://howardhinnant.github.io/date_algorithms.html
var z = epochday
z.inc 719468
let era = (if z >= 0: z else: z - 146096) div 146097
let doe = z - era * 146097
let yoe = (doe - doe div 1460 + doe div 36524 - doe div 146096) div 365
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe div 4 - yoe div 100)
let mp = (5 * doy + 2) div 153
let d = doy - (153 * mp + 2) div 5 + 1
let m = mp + (if mp < 10: 3 else: -9)
return (d.MonthdayRange, m.Month, (y + ord(m <= 2)).int)
proc getDayOfYear*(monthday: MonthdayRange, month: Month, year: int):
YeardayRange {.tags: [], raises: [], benign.} =
## Returns the day of the year.
## Equivalent with ``initDateTime(monthday, month, year, 0, 0, 0).yearday``.
runnableExamples:
doAssert getDayOfYear(1, mJan, 2000) == 0
doAssert getDayOfYear(10, mJan, 2000) == 9
doAssert getDayOfYear(10, mFeb, 2000) == 40
assertValidDate monthday, month, year
const daysUntilMonth: array[Month, int] =
[0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
const daysUntilMonthLeap: array[Month, int] =
[0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]
if isLeapYear(year):
result = daysUntilMonthLeap[month] + monthday - 1
else:
result = daysUntilMonth[month] + monthday - 1
proc getDayOfWeek*(monthday: MonthdayRange, month: Month, year: int): WeekDay
{.tags: [], raises: [], benign.} =
## Returns the day of the week enum from day, month and year.
## Equivalent with ``initDateTime(monthday, month, year, 0, 0, 0).weekday``.
runnableExamples:
doAssert getDayOfWeek(13, mJun, 1990) == dWed
doAssert $getDayOfWeek(13, mJun, 1990) == "Wednesday"
assertValidDate monthday, month, year
# 1970-01-01 is a Thursday, we adjust to the previous Monday
let days = toEpochday(monthday, month, year) - 3
let weeks = floorDiv(days, 7)
let wd = days - weeks * 7
# The value of d is 0 for a Sunday, 1 for a Monday, 2 for a Tuesday, etc.
# so we must correct for the WeekDay type.
result = if wd == 0: dSun else: WeekDay(wd - 1)
{.pragma: operator, rtl, noSideEffect, benign.}
template subImpl[T: Duration|Time](a: Duration|Time, b: Duration|Time): T =
normalize[T](a.seconds - b.seconds, a.nanosecond - b.nanosecond)
template addImpl[T: Duration|Time](a: Duration|Time, b: Duration|Time): T =
normalize[T](a.seconds + b.seconds, a.nanosecond + b.nanosecond)
template ltImpl(a: Duration|Time, b: Duration|Time): bool =
a.seconds < b.seconds or (
a.seconds == b.seconds and a.nanosecond < b.nanosecond)
template lqImpl(a: Duration|Time, b: Duration|Time): bool =
a.seconds < b.seconds or (
a.seconds == b.seconds and a.nanosecond <= b.nanosecond)
template eqImpl(a: Duration|Time, b: Duration|Time): bool =
a.seconds == b.seconds and a.nanosecond == b.nanosecond
const DurationZero* = initDuration() ## \
## Zero value for durations. Useful for comparisons.
##
## .. code-block:: nim
##
## doAssert initDuration(seconds = 1) > DurationZero
## doAssert initDuration(seconds = 0) == DurationZero
proc toParts*(dur: Duration): DurationParts =
## Converts a duration into an array consisting of fixed time units.
##
## Each value in the array gives information about a specific unit of
## time, for example ``result[Days]`` gives a count of days.
##
## This procedure is useful for converting ``Duration`` values to strings.
runnableExamples:
var dp = toParts(initDuration(weeks = 2, days = 1))
doAssert dp[Days] == 1
doAssert dp[Weeks] == 2
doAssert dp[Minutes] == 0
dp = toParts(initDuration(days = -1))
doAssert dp[Days] == -1
var remS = dur.seconds
var remNs = dur.nanosecond.int
# Ensure the same sign for seconds and nanoseconds
if remS < 0 and remNs != 0:
remNs -= convert(Seconds, Nanoseconds, 1)
remS.inc 1
for unit in countdown(Weeks, Seconds):
let quantity = convert(Seconds, unit, remS)
remS = remS mod convert(unit, Seconds, 1)
result[unit] = quantity
for unit in countdown(Milliseconds, Nanoseconds):
let quantity = convert(Nanoseconds, unit, remNs)
remNs = remNs mod convert(unit, Nanoseconds, 1)
result[unit] = quantity
proc stringifyUnit(value: int | int64, unit: TimeUnit): string =
## Stringify time unit with it's name, lowercased
let strUnit = $unit
result = ""
result.add($value)
result.add(" ")
if abs(value) != 1:
result.add(strUnit.toLowerAscii())
else:
result.add(strUnit[0..^2].toLowerAscii())
proc humanizeParts(parts: seq[string]): string =
## Make date string parts human-readable
result = ""
if parts.len == 0:
result.add "0 nanoseconds"
elif parts.len == 1:
result = parts[0]
elif parts.len == 2:
result = parts[0] & " and " & parts[1]
else:
for i in 0..high(parts)-1:
result.add parts[i] & ", "
result.add "and " & parts[high(parts)]
proc `$`*(dur: Duration): string =
## Human friendly string representation of a ``Duration``.
runnableExamples:
doAssert $initDuration(seconds = 2) == "2 seconds"
doAssert $initDuration(weeks = 1, days = 2) == "1 week and 2 days"
doAssert $initDuration(hours = 1, minutes = 2, seconds = 3) ==
"1 hour, 2 minutes, and 3 seconds"
doAssert $initDuration(milliseconds = -1500) ==
"-1 second and -500 milliseconds"
var parts = newSeq[string]()
var numParts = toParts(dur)
for unit in countdown(Weeks, Nanoseconds):
let quantity = numParts[unit]
if quantity != 0.int64:
parts.add(stringifyUnit(quantity, unit))
result = humanizeParts(parts)
proc `+`*(a, b: Duration): Duration {.operator.} =
## Add two durations together.
runnableExamples:
doAssert initDuration(seconds = 1) + initDuration(days = 1) ==
initDuration(seconds = 1, days = 1)
addImpl[Duration](a, b)
proc `-`*(a, b: Duration): Duration {.operator.} =
## Subtract a duration from another.
runnableExamples:
doAssert initDuration(seconds = 1, days = 1) - initDuration(seconds = 1) ==
initDuration(days = 1)
subImpl[Duration](a, b)
proc `-`*(a: Duration): Duration {.operator.} =
## Reverse a duration.
runnableExamples:
doAssert -initDuration(seconds = 1) == initDuration(seconds = -1)
normalize[Duration](-a.seconds, -a.nanosecond)
proc `<`*(a, b: Duration): bool {.operator.} =
## Note that a duration can be negative,
## so even if ``a < b`` is true ``a`` might
## represent a larger absolute duration.
## Use ``abs(a) < abs(b)`` to compare the absolute
## duration.
runnableExamples:
doAssert initDuration(seconds = 1) < initDuration(seconds = 2)
doAssert initDuration(seconds = -2) < initDuration(seconds = 1)
doAssert initDuration(seconds = -2).abs < initDuration(seconds = 1).abs == false
ltImpl(a, b)
proc `<=`*(a, b: Duration): bool {.operator.} =
lqImpl(a, b)
proc `==`*(a, b: Duration): bool {.operator.} =
runnableExamples:
let
d1 = initDuration(weeks = 1)
d2 = initDuration(days = 7)
doAssert d1 == d2
eqImpl(a, b)
proc `*`*(a: int64, b: Duration): Duration {.operator.} =
## Multiply a duration by some scalar.
runnableExamples:
doAssert 5 * initDuration(seconds = 1) == initDuration(seconds = 5)
doAssert 3 * initDuration(minutes = 45) == initDuration(hours = 2, minutes = 15)
normalize[Duration](a * b.seconds, a * b.nanosecond)
proc `*`*(a: Duration, b: int64): Duration {.operator.} =
## Multiply a duration by some scalar.
runnableExamples:
doAssert initDuration(seconds = 1) * 5 == initDuration(seconds = 5)
doAssert initDuration(minutes = 45) * 3 == initDuration(hours = 2, minutes = 15)
b * a
proc `div`*(a: Duration, b: int64): Duration {.operator.} =
## Integer division for durations.
runnableExamples:
doAssert initDuration(seconds = 3) div 2 ==
initDuration(milliseconds = 1500)
doAssert initDuration(minutes = 45) div 30 ==
initDuration(minutes = 1, seconds = 30)
doAssert initDuration(nanoseconds = 3) div 2 ==
initDuration(nanoseconds = 1)
let carryOver = convert(Seconds, Nanoseconds, a.seconds mod b)
normalize[Duration](a.seconds div b, (a.nanosecond + carryOver) div b)
proc initTime*(unix: int64, nanosecond: NanosecondRange): Time =
## Create a `Time <#Time>`_ from a unix timestamp and a nanosecond part.
result.seconds = unix
result.nanosecond = nanosecond
proc `-`*(a, b: Time): Duration {.operator, extern: "ntDiffTime".} =
## Computes the duration between two points in time.
runnableExamples:
doAssert initTime(1000, 100) - initTime(500, 20) ==
initDuration(minutes = 8, seconds = 20, nanoseconds = 80)
subImpl[Duration](a, b)
proc `+`*(a: Time, b: Duration): Time {.operator, extern: "ntAddTime".} =
## Add a duration of time to a ``Time``.
runnableExamples:
doAssert (fromUnix(0) + initDuration(seconds = 1)) == fromUnix(1)
addImpl[Time](a, b)
proc `-`*(a: Time, b: Duration): Time {.operator, extern: "ntSubTime".} =
## Subtracts a duration of time from a ``Time``.
runnableExamples:
doAssert (fromUnix(0) - initDuration(seconds = 1)) == fromUnix(-1)
subImpl[Time](a, b)
proc `<`*(a, b: Time): bool {.operator, extern: "ntLtTime".} =
## Returns true iff ``a < b``, that is iff a happened before b.
runnableExamples:
doAssert initTime(50, 0) < initTime(99, 0)
ltImpl(a, b)
proc `<=`*(a, b: Time): bool {.operator, extern: "ntLeTime".} =
## Returns true iff ``a <= b``.
lqImpl(a, b)
proc `==`*(a, b: Time): bool {.operator, extern: "ntEqTime".} =
## Returns true if ``a == b``, that is if both times represent the same point in time.
eqImpl(a, b)
proc high*(typ: typedesc[Time]): Time =
initTime(high(int64), high(NanosecondRange))
proc low*(typ: typedesc[Time]): Time =
initTime(low(int64), 0)
proc high*(typ: typedesc[Duration]): Duration =
## Get the longest representable duration.
initDuration(seconds = high(int64), nanoseconds = high(NanosecondRange))
proc low*(typ: typedesc[Duration]): Duration =
## Get the longest representable duration of negative direction.
initDuration(seconds = low(int64))
proc abs*(a: Duration): Duration =
runnableExamples:
doAssert initDuration(milliseconds = -1500).abs ==
initDuration(milliseconds = 1500)
initDuration(seconds = abs(a.seconds), nanoseconds = -a.nanosecond)
proc toTime*(dt: DateTime): Time {.tags: [], raises: [], benign.} =
## Converts a ``DateTime`` to a ``Time`` representing the same point in time.
let epochDay = toEpochday(dt.monthday, dt.month, dt.year)
var seconds = epochDay * secondsInDay
seconds.inc dt.hour * secondsInHour
seconds.inc dt.minute * 60
seconds.inc dt.second
seconds.inc dt.utcOffset
result = initTime(seconds, dt.nanosecond)
proc initDateTime(zt: ZonedTime, zone: Timezone): DateTime =
## Create a new ``DateTime`` using ``ZonedTime`` in the specified timezone.
let adjTime = zt.time - initDuration(seconds = zt.utcOffset)
let s = adjTime.seconds
let epochday = floorDiv(s, secondsInDay)
var rem = s - epochday * secondsInDay
let hour = rem div secondsInHour
rem = rem - hour * secondsInHour
let minute = rem div secondsInMin
rem = rem - minute * secondsInMin
let second = rem
let (d, m, y) = fromEpochday(epochday)
DateTime(
year: y,
month: m,
monthday: d,
hour: hour,
minute: minute,
second: second,
nanosecond: zt.time.nanosecond,
weekday: getDayOfWeek(d, m, y),
yearday: getDayOfYear(d, m, y),
isDst: zt.isDst,
timezone: zone,
utcOffset: zt.utcOffset
)
proc newTimezone*(
name: string,
zonedTimeFromTimeImpl: proc (time: Time): ZonedTime
{.tags: [], raises: [], benign.},
zonedTimeFromAdjTimeImpl: proc (adjTime: Time): ZonedTime
{.tags: [], raises: [], benign.}
): owned Timezone =
## Create a new ``Timezone``.
##
## ``zonedTimeFromTimeImpl`` and ``zonedTimeFromAdjTimeImpl`` is used
## as the underlying implementations for ``zonedTimeFromTime`` and
## ``zonedTimeFromAdjTime``.
##
## If possible, the name parameter should match the name used in the
## tz database. If the timezone doesn't exist in the tz database, or if the
## timezone name is unknown, then any string that describes the timezone
## unambiguously can be used. Note that the timezones name is used for
## checking equality!
runnableExamples:
proc utcTzInfo(time: Time): ZonedTime =
ZonedTime(utcOffset: 0, isDst: false, time: time)
let utc = newTimezone("Etc/UTC", utcTzInfo, utcTzInfo)
Timezone(
name: name,
zonedTimeFromTimeImpl: zonedTimeFromTimeImpl,
zonedTimeFromAdjTimeImpl: zonedTimeFromAdjTimeImpl
)
proc name*(zone: Timezone): string =
## The name of the timezone.
##