/
time.cr
1430 lines (1269 loc) · 46 KB
/
time.cr
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
require "crystal/system/time"
# `Time` represents a date-time instant in
# [incremental time](https://www.w3.org/International/articles/definitions-time/#incremental_time)
# observed in a specific time zone.
#
# The calendaric calculations are based on the rules of the proleptic Gregorian
# calendar as specified in [ISO 8601](http://xml.coverpages.org/ISO-FDIS-8601.pdf).
# Leap seconds are ignored.
#
# Internally, the time is stored as an `Int64` representing seconds from epoch
# (`0001-01-01 00:00:00.0 UTC`) and an `Int32` representing
# nanosecond-of-second with value range `0..999_999_999`.
#
# The supported date range is `0001-01-01 00:00:00.0` to
# `9999-12-31 23:59:59.999_999_999` in any local time zone.
#
# ### Telling the Time
#
# There are several methods to retrieve a `Time` instance representing the
# current time:
#
# ```crystal
# Time.utc_now # returns the current time in UTC
# Time.now Time::Location.load("Europe/Berlin") # returns the current time in time zone Europe/Berlin
# Time.now # returns the current time in current time zone
# ```
#
# It is generally recommended to keep instances in UTC and only apply a
# local time zone when formatting for user display, unless the domain logic
# requires having a specific time zone (for example for calendaric operations).
#
# ### Creating a Specific Instant
#
# `Time` instances representing a specific instant can be created by
# `.utc` or `.new` with the date-time specified as individual arguments:
#
# ```
# time = Time.utc(2016, 2, 15, 10, 20, 30)
# time.to_s # => 2016-02-15 10:20:30 UTC
# time = Time.new(2016, 2, 15, 10, 20, 30, location: Time::Location.load("Europe/Berlin"))
# time.to_s # => 2016-02-15 10:20:30 +01:00 Europe/Berlin
# # The time-of-day can be omitted and defaults to midnight (start of day):
# time = Time.utc(2016, 2, 15)
# time.to_s # => 2016-02-15 00:00:00 UTC
# ```
#
# ### Retrieving Time Information
#
# Each `Time` instance allows querying calendar data:
#
# ```
# time = Time.utc(2016, 2, 15, 10, 20, 30)
# time.year # => 2016
# time.month # => 2
# time.day # => 15
# time.hour # => 10
# time.minute # => 20
# time.second # => 30
# time.millisecond # => 0
# time.nanosecond # => 0
# time.day_of_week # => Time::DayOfWeek::Monday
# time.day_of_year # => 46
# time.monday? # => true
# time.time_of_day # => 10:20:30
# ```
#
# For querying if a time is at a specific day of week, `Time` offers named
# predicate methods, delegating to `#day_of_week`:
#
# ```
# time.monday? # => true
# # ...
# time.sunday? # => false
# ```
#
# ### Time Zones
#
# Each time is attached to a specific time zone, represented by a `Location`
# (see `#location`).
# `#zone` returns the time zone observed in this location at the current time
# (i.e. the instant represented by this `Time`).
# `#offset` returns the offset of the current zone in seconds.
#
# ```
# time = Time.new(2018, 3, 8, 22, 5, 13, location: Time::Location.load("Europe/Berlin"))
# time # => 2018-03-08 22:05:13 +01:00 Europe/Berlin
# time.location # => #<Time::Location Europe/Berlin>
# time.zone # => #<Time::Location::Zone CET +01:00 (3600s) STD>
# time.offset # => 3600
# ```
#
# Using `.utc`, the location is `Time::Location::UTC`:
#
# ```
# time = Time.utc(2018, 3, 8, 22, 5, 13)
# time # => 2018-03-08 22:05:13.0 UTC
# time.location # => #<Time::Location UTC>
# time.zone # => #<Time::Location::Zone UTC +00:00 (0s) STD>
# time.offset # => 0
# ```
#
# A `Time` instance can be transformed to a different time zone while retaining
# the same instant using `#in`:
#
# ```
# time_de = Time.new(2018, 3, 8, 22, 5, 13, location: Time::Location.load("Europe/Berlin"))
# time_ar = time_de.in Time::Location.load("America/Buenos_Aires")
# time_de # => 2018-03-08 22:05:13 +01:00 Europe/Berlin
# time_ar # => 2018-03-08 18:05:13 -03:00 America/Buenos_Aires
# ```
#
# Both `Time` instances show a different local date-time, but they represent
# the same date-time in the instant time-line, therefore they are considered
# equal:
#
# ```
# time_de.to_utc # => 2018-03-08 21:05:13 UTC
# time_ar.to_utc # => 2018-03-08 21:05:13 UTC
# time_de == time_ar # => true
# ```
#
# There are also two special methods for converting to UTC and local time zone:
#
# ```
# time.to_utc # equals time.in(Location::UTC)
# time.to_local # equals time.in(Location.local)
# ```
#
# `#to_local_in` allows changing the time zone while keeping
# the same local date-time (wall clock) which results in a different instant
# on the time line.
#
# ### Formatting and Parsing Time
#
# To make date-time instances exchangeable between different computer systems
# or readable to humans, they are usually converted to and from a string
# representation.
#
# The method `#to_s` formats the date-time according to a specified pattern.
#
# ```
# time = Time.utc(2015, 10, 12, 10, 30, 0)
# time.to_s("%Y-%m-%d %H:%M:%S %:z") # => "2015-10-12 10:30:00 +00:00"
# ```
#
# Similarly, `Time.parse` and `Time.parse!` are used to construct a `Time` instance from date-time
# information in a string, according to a specified pattern:
#
# ```
# Time.parse("2015-10-12 10:30:00 +00:00", "%Y-%m-%d %H:%M:%S %z", Time::Location::UTC)
# Time.parse!("2015-10-12 10:30:00 +00:00", "%Y-%m-%d %H:%M:%S %z")
# ```
#
# See `Time::Format` for all directives.
#
# ### Calculations
#
# ```
# Time.utc(2015, 10, 10) - 5.days # => 2015-10-05 00:00:00 +00:00
#
# span = Time.utc(2015, 10, 10) - Time.utc(2015, 9, 10)
# span.days # => 30
# span.total_hours # => 720
# span.total_minutes # => 43200
# ```
#
# ## Measuring Time
#
# The typical time representation provided by the operating system is based on
# a "wall clock" which is subject to changes for clock synchronization.
# This can result in discontinuous jumps in the time-line making it not
# suitable for accurately measuring elapsed time.
#
# Instances of `Time` are focused on telling time – using a "wall clock".
# When `Time.now` is called multiple times, the difference between the
# returned instances is not guranteed to equal to the time elapsed between
# making the calls; even the order of the returned `Time` instances might
# not reflect invocation order.
#
# ```
# t1 = Time.utc_now
# # operation that takes 1 minute
# t2 = Time.utc_now
# t2 - t1 # => ?
# ```
#
# The resulting `Time::Span` could be anything, even negative, if the
# computer's wall clock has changed between both calls.
#
# As an alternative, the operating system also provides a monotonic clock.
# Its time-line has no specfied starting point but is strictly linearly
# increasing.
#
# This monotonic clock should always be used for measuring elapsed time.
#
# A reading from this clock can be taken using `.monotonic`:
#
# ```
# t1 = Time.monotonic
# # operation that takes 1 minute
# t2 = Time.monotonic
# t2 - t1 # => 1.minute (approximately)
# ```
#
# The execution time of a block can be measured using `.measure`:
#
# ```
# elapsed_time = Time.measure do
# # operation that takes 20 milliseconds
# end
# elapsed_time # => 20.milliseconds (approximately)
# ```
struct Time
class FloatingTimeConversionError < Exception
end
include Comparable(Time)
# :nodoc:
DAYS_MONTH = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
# :nodoc:
DAYS_MONTH_LEAP = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
# :nodoc:
SECONDS_PER_MINUTE = 60
# :nodoc:
SECONDS_PER_HOUR = 60 * SECONDS_PER_MINUTE
# :nodoc:
SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR
# :nodoc:
SECONDS_PER_WEEK = 7 * SECONDS_PER_DAY
# :nodoc:
NANOSECONDS_PER_MILLISECOND = 1_000_000_i64
# :nodoc:
NANOSECONDS_PER_MICROSECOND = 1_000_i64
# :nodoc:
NANOSECONDS_PER_SECOND = 1_000_000_000_i64
# :nodoc:
NANOSECONDS_PER_MINUTE = NANOSECONDS_PER_SECOND * 60
# :nodoc:
NANOSECONDS_PER_HOUR = NANOSECONDS_PER_MINUTE * 60
# :nodoc:
NANOSECONDS_PER_DAY = NANOSECONDS_PER_HOUR * 24
# :nodoc:
DAYS_PER_400_YEARS = 365*400 + 97
# :nodoc:
DAYS_PER_100_YEARS = 365*100 + 24
# :nodoc:
DAYS_PER_4_YEARS = 365*4 + 1
# This constant is defined to be "1970-01-01 00:00:00 UTC".
# Can be used to create a `Time::Span` that represents an Unix Epoch time duration.
#
# ```
# Time.utc_now - Time::UNIX_EPOCH
# ```
UNIX_EPOCH = utc(1970, 1, 1)
# :nodoc:
MAX_SECONDS = 315537897599_i64
# `DayOfWeek` represents a day of the week in the Gregorian calendar.
#
# ```
# time = Time.new(2016, 2, 15)
# time.day_of_week # => Time::DayOfWeek::Monday
# ```
#
# Each member is identified by its ordinal number starting from `Monday = 1`
# according to [ISO 8601](http://xml.coverpages.org/ISO-FDIS-8601.pdf).
#
# `#value` returns this ordinal number. It can easily be converted to the also
# common numbering based on `Sunday = 0` using `value % 7`.
enum DayOfWeek
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6
Sunday = 7
# Returns the day of week that has the given value, or raises if no such member exists.
#
# This method also accepts `0` to identify `Sunday` in order to be compliant
# with the `Sunday = 0` numbering. All other days are equal in both formats.
def self.from_value(value : Int32) : self
value = 7 if value == 0
super(value)
end
end
@seconds : Int64
@nanoseconds : Int32
# Returns `Location` representing the time-zone observed by this `Time`.
getter location : Location
# Returns a reading from the monotonic clock to measure elapsed time.
#
# Values from the monotonic clock and wall clock are not comparable.
# This method does not return a `Time` instance but a `Time::Span` amounting
# to the number of nanoseconds elapsed since the unspecified starting point
# of the monotonic clock.
# The returned values are strictly linearly increasing.
#
# This clock should be independent from discontinuous jumps in the
# system time, such as leap seconds, time zone adjustments or manual changes
# to the computer's clock.
#
# Subtracting two results from this method equals to the time elapsed between
# both readings:
#
# ```
# start = Time.monotonic
# # operation that takes 20 milliseconds
# elapsed = Time.monotonic - start # => 20.milliseconds (approximately)
# # operation that takes 50 milliseconds
# elapsed_total = Time.monotonic - start # => 70.milliseconds (approximately)
# ```
#
# The execution time of a block can be measured using `.measure`.
def self.monotonic : Time::Span
seconds, nanoseconds = Crystal::System::Time.monotonic
Time::Span.new(seconds: seconds, nanoseconds: nanoseconds)
end
# Measures the execution time of *block*.
#
# The measurement relies on the monotonic clock and is not
# affected by fluctuations of the system clock (see `#monotonic`).
#
# ```
# elapsed_time = Time.measure do
# # operation that takes 20 milliseconds
# end
# elapsed_time # => 20.milliseconds (approximately)
# ```
def self.measure(&block : ->) : Time::Span
start = monotonic
yield
monotonic - start
end
# Creates a new `Time` instance representing the current time from the
# system clock observed in *location* (defaults to local time zone).
def self.new(location : Location = Location.local) : Time
seconds, nanoseconds = Crystal::System::Time.compute_utc_seconds_and_nanoseconds
new(seconds: seconds, nanoseconds: nanoseconds, location: location)
end
# Creates a new `Time` instance representing the current time from the
# system clock observed in *location* (defaults to local time zone).
def self.now(location : Location = Location.local) : Time
new(location)
end
# Creates a new `Time` instance representing the current time from the
# system clock in UTC.
def self.utc_now : Time
now(Location::UTC)
end
# Creates a new `Time` instance representing the given local date-time in
# *location* (defaults to local time zone).
#
# ```
# time = Time.new(2016, 2, 15, 10, 20, 30, location: Time::Location.load("Europe/Berlin"))
# time.inspect # => "2016-02-15 10:20:30.0 +01:00 Europe/Berlin"
# ```
#
# Valid value ranges for the individual fields:
#
# * `year`: `1..9999`
# * `month`: `1..12`
# * `day`: `1` - `28`/`29`/`30`/`31` (depending on month and year)
# * `hour`: `0..23`
# * `minute`: `0..59`
# * `second`: `0..59`
# * `nanosecond`: `0..999_999_999`
#
# The time-of-day can be omitted and defaults to midnight (start of day):
#
# ```
# time = Time.new(2016, 2, 15)
# time.to_s # => "2016-02-15 00:00:00 +00:00"
# ```
#
# The local date-time representation is resolved to a single instant based on
# the offset observed in the *location* at this time.
#
# This process can sometimes be ambiguous, mostly due skipping or repeating
# times at time zone transitions. For example, in `America/New_York` the
# date-time `2011-03-13 02:15:00` never occured, there is a gap between time
# zones. In return, `2011-11-06 01:15:00` occured twice because of overlapping
# time zones.
#
# In such cases, the choice of time zone, and therefore the time, is not
# well-defined. This method returns a time that is correct in one of the two
# zones involved in the transition, but it does not guarantee which.
def self.new(year : Int32, month : Int32, day : Int32, hour : Int32 = 0, minute : Int32 = 0, second : Int32 = 0, *, nanosecond : Int32 = 0, location : Location = Location.local) : Time
unless 1 <= year <= 9999 &&
1 <= month <= 12 &&
1 <= day <= Time.days_in_month(year, month) &&
0 <= hour <= 23 &&
0 <= minute <= 59 &&
0 <= second <= 59 &&
0 <= nanosecond <= 999_999_999
raise ArgumentError.new "Invalid time"
end
days = absolute_days(year, month, day)
seconds = 1_i64 *
SECONDS_PER_DAY * days +
SECONDS_PER_HOUR * hour +
SECONDS_PER_MINUTE * minute +
second
# Normalize internal representation to UTC
seconds = seconds - zone_offset_at(seconds, location) if !location.utc?
new(seconds: seconds, nanoseconds: nanosecond.to_i, location: location)
end
# Creates a new `Time` instance representing the given date-time in UTC.
#
# ```
# time = Time.utc(2016, 2, 15, 10, 20, 30)
# time.to_s # => "2016-02-15 10:20:30 UTC"
# ```
#
# Valid value ranges for the individual fields:
#
# * `year`: `1..9999`
# * `month`: `1..12`
# * `day`: `1` - `28`/`29`/`30`/`31` (depending on month and year)
# * `hour`: `0..23`
# * `minute`: `0..59`
# * `second`: `0..59`
# * `nanosecond`: `0..999_999_999`
#
# The time-of-day can be omitted and defaults to midnight (start of day):
#
# ```
# time = Time.utc(2016, 2, 15)
# time.to_s # => "2016-02-15 00:00:00 UTC"
# ```
#
# Since UTC does not have any time zone transitions, each date-time is
# unambiguously resolved.
def self.utc(year : Int32, month : Int32, day : Int32, hour : Int32 = 0, minute : Int32 = 0, second : Int32 = 0, *, nanosecond : Int32 = 0) : Time
new(year, month, day, hour, minute, second, nanosecond: nanosecond, location: Location::UTC)
end
# Creates a new `Time` instance that corresponds to the number of *seconds*
# and *nanoseconds* elapsed from epoch (`0001-01-01 00:00:00.0 UTC`)
# observed in *location*.
#
# Valid range for *seconds* is `0..315_537_897_599`.
# For *nanoseconds* it is `0..999_999_999`.
def initialize(*, @seconds : Int64, @nanoseconds : Int32, @location : Location)
unless 0 <= offset_seconds <= MAX_SECONDS
raise ArgumentError.new "Invalid time: seconds out of range"
end
unless 0 <= @nanoseconds < NANOSECONDS_PER_SECOND
raise ArgumentError.new "Invalid time: nanoseconds out of range"
end
end
# Creates a new `Time` instance that corresponds to the number of *seconds*
# and *nanoseconds* elapsed from epoch (`0001-01-01 00:00:00.0 UTC`)
# in UTC.
#
# Valid range for *seconds* is `0..315_537_897_599`.
# For *nanoseconds* it is `0..999_999_999`.
def self.utc(*, seconds : Int64, nanoseconds : Int32) : Time
new(seconds: seconds, nanoseconds: nanoseconds, location: Location::UTC)
end
{% unless flag?(:win32) %}
# :nodoc:
def self.new(time : LibC::Timespec, location : Location = Location.local)
seconds = UNIX_EPOCH.total_seconds + time.tv_sec
nanoseconds = time.tv_nsec.to_i
new(seconds: seconds, nanoseconds: nanoseconds, location: location)
end
{% end %}
# Creates a new `Time` instance that corresponds to the number of
# *seconds* elapsed since the Unix epoch (`1970-01-01 00:00:00 UTC`).
#
# The time zone is always UTC.
#
# ```
# Time.unix(981173106) # => 2001-02-03 04:05:06 UTC
# ```
def self.unix(seconds : Int) : Time
utc(seconds: UNIX_EPOCH.total_seconds + seconds, nanoseconds: 0)
end
# Creates a new `Time` instance that corresponds to the number of
# *milliseconds* elapsed since the Unix epoch (`1970-01-01 00:00:00 UTC`).
#
# The time zone is always UTC.
#
# ```
# time = Time.unix_ms(981173106789) # => 2001-02-03 04:05:06.789 UTC
# time.millisecond # => 789
# ```
def self.unix_ms(milliseconds : Int) : Time
milliseconds = milliseconds.to_i64
seconds = UNIX_EPOCH.total_seconds + (milliseconds / 1_000)
nanoseconds = (milliseconds % 1000) * NANOSECONDS_PER_MILLISECOND
utc(seconds: seconds, nanoseconds: nanoseconds.to_i)
end
# Creates a new `Time` instance with the same local date-time representation
# (wall clock) in a different *location*.
#
# Unlike `#in`, which always preserves the same instant in time, `#to_local_in`
# adjusts the instant such that it results in the same local date-time
# representation. Both instants are apart from each other by the difference in
# zone offsets.
#
# ```
# new_year = Time.utc(2019, 1, 1, 0, 0, 0)
# tokyo = new_year.to_local_in(Time::Location.load("Asia/Tokyo"))
# new_york = new_year.to_local_in(Time::Location.load("America/New_York"))
# tokyo.to_s # => 2019-01-01 00:00:00.0 +09:00 Asia/Tokyo
# new_york.to_s # => 2019-01-01 00:00:00.0 -05:00 America/New_York
# ```
def to_local_in(location : Location)
local_seconds = offset_seconds
local_seconds -= Time.zone_offset_at(local_seconds, location)
Time.new(seconds: local_seconds, nanoseconds: nanosecond, location: location)
end
def clone : Time
self
end
# Returns a copy of this `Time` with *span* added.
#
# See `#add_span` for details.
def +(span : Time::Span) : Time
add_span span.to_i, span.nanoseconds
end
# Returns a copy of this `Time` with *span* subtracted.
#
# See `#add_span` for details.
def -(span : Time::Span) : Time
add_span -span.to_i, -span.nanoseconds
end
# Returns a copy of this `Time` with *span* added.
#
# It adds the number of months with overflow increasing the year.
# If the resulting day-of-month would be invalid, it is adjusted to the last
# valid day of the moneth.
#
# For example, adding `1.month` to `2007-03-31` would result in the invalid
# date `2007-04-31` which will be adjusted to `2007-04-30`.
#
# This operates on the local time-line, such that the local date-time
# represenations of month and year are increased by the specified amount.
#
# If the resulting date-time is ambiguous due to time zone transitions,
# a correct time will be returned, but it does not guarantee which.
def +(span : Time::MonthSpan) : Time
add_months span.value
end
# Returns a copy of this `Time` with *span* subtracted.
#
# It adds the number of months with overflow decreasing the year.
# If the resulting day-of-month would be invalid, it is adjusted to the last
# valid day of the moneth.
#
# For example, subtracting `1.month` from `2007-05-31` would result in the invalid
# date `2007-04-31` which will be adjusted to `2007-04-30`.
#
# This operates on the local time-line, such that the local date-time
# represenations of month and year are decreased by the specified amount.
#
# If the resulting date-time is ambiguous due to time zone transitions,
# a correct time will be returned, but it does not guarantee which.
def -(span : Time::MonthSpan) : Time
add_months -span.value
end
private def add_months(months)
day = self.day
month = self.month + months.remainder(12)
year = self.year + months.tdiv(12)
if month < 1
month = 12 + month
year -= 1
elsif month > 12
month = month - 12
year += 1
end
maxday = Time.days_in_month(year, month)
if day > maxday
day = maxday
end
temp = Time.new(year, month, day, location: location)
temp + time_of_day
end
# Returns a copy of this `Time` with the number of *seconds* and
# *nanoseconds* added.
#
# Positive values result in a later time, negative values in an earlier time.
#
# This operates on the instant time-line, such that adding the eqivalent of
# one hour will always be a duration of one hour later.
# The local date-time representation may change by a different amount,
# depending on time zone transitions.
#
# Overflow in *nanoseconds* will be transferred to *seconds*.
#
# There is no explicit limit on the input values but the addition must result
# in a valid time between `0001-01-01 00:00:00.0` and
# `9999-12-31 23:59:59.999_999_999`. Otherwise `ArgumentError` is raised.
def add_span(seconds : Int, nanoseconds : Int) : Time
if seconds == 0 && nanoseconds == 0
return self
end
seconds = total_seconds + seconds
nanoseconds = self.nanosecond.to_i64 + nanoseconds
# Nanoseconds might end up outside the min/max nanosecond
# range, so take care of that
seconds += nanoseconds.tdiv(NANOSECONDS_PER_SECOND)
nanoseconds = nanoseconds.remainder(NANOSECONDS_PER_SECOND)
if nanoseconds < 0
seconds -= 1
nanoseconds += NANOSECONDS_PER_SECOND
end
Time.new(seconds: seconds, nanoseconds: nanoseconds.to_i, location: location)
end
# Returns a `Time::Span` amounting to the duration between *other* and `self`.
#
# The time span is negative if `self` is before *other*.
#
# The duration amounts to the actual time elapsed between both instances, on
# the instant time-line.
# The difference between local date-time representations may equal to a
# different duration, depending on time zone transitions.
def -(other : Time) : Time::Span
Span.new(
seconds: total_seconds - other.total_seconds,
nanoseconds: nanosecond - other.nanosecond,
)
end
# Returns a copy of `self` with time-of-day components (hour, minute, second,
# nanoseconds) set to zero.
#
# This equals `at_beginning_of_day` or
# `Time.new(year, month, day, 0, 0, 0, nanoseconds: 0, location: location)`.
def date : Time
Time.new(year, month, day, location: location)
end
# Returns the year of the proleptic Georgian Calendar (`0..9999`).
def year : Int32
year_month_day_day_year[0]
end
# Returns the month of the year (`1..12`).
def month : Int32
year_month_day_day_year[1]
end
# Returns the day of the month (`1..31`).
def day : Int32
year_month_day_day_year[2]
end
# Returns the hour of the day (`0..23`).
def hour : Int32
((offset_seconds % SECONDS_PER_DAY) / SECONDS_PER_HOUR).to_i
end
# Returns the minute of the hour (`0..59`).
def minute : Int32
((offset_seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE).to_i
end
# Returns the second of the minute (`0..59`).
def second : Int32
(offset_seconds % SECONDS_PER_MINUTE).to_i
end
# Returns the millisecond of the second (`0..999`).
def millisecond : Int32
nanosecond / NANOSECONDS_PER_MILLISECOND
end
# Returns the nanosecond of the second (`0..999_999_999`).
def nanosecond : Int32
@nanoseconds
end
# Returns the ISO calendar year and week in which this instance occurs.
#
# The ISO calendar year to which the week belongs is not always in the same
# as the year of the regular calendar date. The first three days of January
# sometimes belong to week 52 (or 53) of the previous year;
# equally the last three days of December sometimes are already in week 1
# of the following year.
#
# For that reason, this method returns a tuple `year, week` consisting of the
# calendar year to which the calendar week belongs and the ordinal number of
# the week within that year.
#
# Together with `#day_of_week` this represents a specific day as commercial or
# week date format `year, week, day_of_week` in the same way as the typical
# format `year, month, day`.
# `.week_date` creates a `Time` instance from a week date.
def calendar_week : {Int32, Int32}
year, month, day, day_year = year_month_day_day_year
day_of_week = self.day_of_week
# The week number can be calculated as number of Mondays in the year up to
# the ordinal date.
# The addition by +10 consists of +7 to start the week numbering with 1
# instead of 0 and +3 because the first week has already started in the
# previous year and the first Monday is actually in week 2.
week_number = (day_year - day_of_week.to_i + 10) / 7
if week_number == 0
# Week number 0 means the date belongs to the last week of the previous year.
year -= 1
# The week number depends on whether the previous year has 52 or 53 weeks
# which can be determined by the day of week of January 1.
# The year has 53 weeks if Januar 1 is on a Friday or the year was a leap
# year and January 1 is on a Saturday.
jan1_day_of_week = DayOfWeek.from_value((day_of_week.to_i - day_year + 1) % 7)
if jan1_day_of_week == DayOfWeek::Friday || (jan1_day_of_week == DayOfWeek::Saturday && Time.leap_year?(year))
week_number = 53
else
week_number = 52
end
elsif week_number == 53
# Week number 53 is actually week number 1 of the following year, if
# December 31 is on a Monday, Tuesday or Wednesday.
dec31_day_of_week = (day_of_week.to_i + 31 - day) % 7
if dec31_day_of_week <= DayOfWeek::Wednesday.to_i
year += 1
week_number = 1
end
end
{year, week_number}
end
# Creates an instance specified by a commercial week date consisting of ISO
# calendar *year*, *week* and a *day_of_week*.
#
# This equates to the results from `#calendar_week` and `#day_of_week`.
#
# Valid value ranges for the individual fields:
#
# * `year`: `1..9999`
# * `week`: `1..53`
# * `day_of_week`: `1..7`
def self.week_date(year : Int32, week : Int32, day_of_week : Int32 | DayOfWeek, hour : Int32 = 0, minute : Int32 = 0, second : Int32 = 0, *, nanosecond : Int32 = 0, location : Location = Location.local) : self
# For this calculation we need to know the weekday of Januar 4.
# The number of the day plus a fixed offset of 4 gives a correction value
# for this year.
jan4_day_of_week = Time.utc(year, 1, 4).day_of_week
correction = jan4_day_of_week.to_i + 4
# The number of weeks multiplied by 7 plus the day of week and the calculated
# correction value results in the ordinal day of the year.
ordinal = week * 7 + day_of_week.to_i - correction
# Adjust the year if the year of the week date does not correspond with the calendar year around New Years.
if ordinal < 1
# If the ordinal day is zero or negative, the date belongs to the previous
# calendar year.
year -= 1
ordinal += Time.days_in_year(year)
elsif ordinal > (days_in_year = Time.days_in_year(year))
# If the ordinal day is greater than the number of days in the year, the date
# belongs to the next year.
ordinal -= days_in_year
year += 1
end
# The ordinal day together with the year fully specifies the date.
# A new instance for January 1 plus the ordinal days results in the correct date.
# This calculation needs to be in UTC to avoid issues with changes in
# the time zone offset (such as daylight savings time).
# TODO: Use #shift or #to_local_in instead
time = Time.utc(year, 1, 1, hour, minute, second, nanosecond: nanosecond) + ordinal.days
# If the location is UTC, we're done
return time if location.utc?
# otherwise, transfer to the specified location without changing the time of day.
time = time.in(location: location)
time - time.offset.seconds
end
# Returns the duration between this `Time` and midnight of the same day.
#
# This is equivalent to creating a `Time::Span` from the time-of-day fields:
#
# ```
# time.time_of_day == Time::Span.new(time.hour, time.minute, time.second, time.nanosecond)
# ```
def time_of_day : Time::Span
Span.new(nanoseconds: NANOSECONDS_PER_SECOND * (offset_seconds % SECONDS_PER_DAY) + nanosecond)
end
# Returns the day of the week (`Monday..Sunday`).
def day_of_week : Time::DayOfWeek
days = offset_seconds / SECONDS_PER_DAY
DayOfWeek.new days.to_i % 7 + 1
end
# Returns the day of the year.
#
# The value range is `1..365` in normal yars and `1..366` in leap years.
def day_of_year : Int32
year_month_day_day_year[3]
end
# Returns the time zone in effect in `location` at this instant.
def zone : Time::Location::Zone
location.lookup(self)
end
# Returns the offset from UTC (in seconds) in effect in `location` at
# this instant.
def offset : Int32
zone.offset
end
# Returns `true` if `#location` equals to `Location::UTC`.
def utc? : Bool
location.utc?
end
# Returns `true` if `#location` equals to the local time zone
# (`Time::Location.local`).
#
# Since the system's settings may change during a program's runtime,
# the result may not be identical between different invocations.
def local? : Bool
location.local?
end
# Compares this `Time` with *other*.
#
# The comparison is based on the instant time-line, even if the local
# date-time representation (wall clock) would compare differently.
#
# To ensure the comparison is also true for local wall clock, both date-times
# need to be transformed to the same time zone.
def <=>(other : Time) : Int32
cmp = total_seconds <=> other.total_seconds
cmp = nanosecond <=> other.nanosecond if cmp == 0
cmp
end
# Compares this `Time` with *other* for equality.
#
# Two instances are considered equal if they represent the same date-time in
# the instant time-line, even if they show a different local date-time.
#
# ```
# time_de = Time.new(2018, 3, 8, 22, 5, 13, location: Time::Location.load("Europe/Berlin"))
# time_ar = Time.new(2018, 3, 8, 18, 5, 13, location: Time::Location.load("America/Buenos_Aires"))
# time_de == time_ar # => true
#
# # both times represent the same instant:
# time_de.to_utc # => 2018-03-08 21:05:13 UTC
# time_ar.to_utc # => 2018-03-08 21:05:13 UTC
# ```
def ==(other : Time) : Bool
total_seconds == other.total_seconds && nanosecond == other.nanosecond
end
def_hash total_seconds, nanosecond
# Returns the number of days in *month* (value range: `1..12`) taking account
# of the *year*.
#
# The returned value is either `28`, `29`, `30` or `31` depending on the
# month and whether *year* is leap.
#
# ```
# Time.days_in_month(2016, 2) # => 29
# Time.days_in_month(1990, 4) # => 30
# ```
def self.days_in_month(year : Int, month : Int) : Int32
unless 1 <= month <= 12
raise ArgumentError.new "Invalid month"
end
unless 1 <= year <= 9999
raise ArgumentError.new "Invalid year"
end
days = leap_year?(year) ? DAYS_MONTH_LEAP : DAYS_MONTH
days[month]
end
# Returns the number of days in *year*.
#
# A normal year has `365` days, a leap year `366` days.
#
# ```
# Time.days_in_year(1990) # => 365
# Time.days_in_year(2004) # => 366
# ```
def self.days_in_year(year : Int) : Int32
leap_year?(year) ? 366 : 365
end
# Returns `true` if *year* is a leap year in the proleptic Gregorian
# calendar.
def self.leap_year?(year : Int) : Bool
unless 1 <= year <= 9999
raise ArgumentError.new "Invalid year"
end
year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
end
# Prints this `Time` to *io*.
#
# The local date-time is formatted as date string `YYYY-MM-DD HH:mm:ss.nnnnnnnnn +ZZ:ZZ:ZZ`.
# Nanoseconds are omitted if *with_nanoseconds* is `false`.
# When the location is `UTC`, the offset is omitted. Offset seconds are omitted if `0`.
#
# The name of the location is appended unless it is a fixed zone offset.
def inspect(io : IO, with_nanoseconds = true)
to_s "%F %T", io
if with_nanoseconds
if @nanoseconds == 0
io << ".0"
else
to_s ".%N", io
end
end
if utc?
io << " UTC"
else
io << ' '
zone.format(io)
io << ' ' << location.name unless location.fixed?
end
io
end
# Prints this `Time` to *io*.
#
# The local date-time is formatted as date string `YYYY-MM-DD HH:mm:ss +ZZ:ZZ:ZZ`.
# Nanoseconds are always omitted.
# When the location is `UTC`, the offset is replaced with the string `UTC`.
# Offset seconds are omitted if `0`.
def to_s(io : IO)