-
Notifications
You must be signed in to change notification settings - Fork 382
/
timex.ex
2039 lines (1620 loc) · 61.4 KB
/
timex.ex
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
defmodule Timex do
@moduledoc File.read!("README.md")
use Application
@doc false
def start(_type, _args) do
apps = Application.started_applications()
tzdata_started? = Enum.find(apps, &(elem(&1, 0) == :tzdata)) != nil
cond do
tzdata_started? ->
case Calendar.get_time_zone_database() do
Calendar.UTCOnlyTimeZoneDatabase ->
Calendar.put_time_zone_database(Timex.Timezone.Database)
_ ->
:ok
end
Supervisor.start_link([], strategy: :one_for_one, name: Timex.Supervisor)
:else ->
{:error, ":tzdata application not started! Ensure :timex is in your applications list!"}
end
end
defmacro __using__(_) do
quote do
alias Timex.AmbiguousDateTime
alias Timex.TimezoneInfo
alias Timex.AmbiguousTimezoneInfo
alias Timex.Interval
alias Timex.Duration
alias Timex.Timezone
end
end
alias Timex.{Duration, AmbiguousDateTime}
alias Timex.{Timezone, TimezoneInfo, AmbiguousTimezoneInfo}
alias Timex.{Types, Helpers, Translator}
alias Timex.{Comparable}
use Timex.Constants
import Timex.Macros
@doc """
Returns a Date representing the current day in UTC
"""
@spec today() :: Date.t()
defdelegate today(), to: Date, as: :utc_today
@doc """
Returns a Date representing the current day in the provided timezone.
"""
@spec today(Types.valid_timezone()) :: Date.t()
def today(timezone), do: now(timezone) |> DateTime.to_date()
@doc """
Returns a DateTime representing the current moment in time in UTC
"""
@spec now() :: DateTime.t()
defdelegate now(), to: DateTime, as: :utc_now
@doc """
Returns a DateTime representing the current moment in time in the provided
timezone.
"""
@spec now(Types.valid_timezone()) :: DateTime.t() | {:error, term}
def now(tz) do
with tzname when is_binary(tzname) <- Timezone.name_of(tz),
{:ok, dt} <- DateTime.now(tzname, Timex.Timezone.Database) do
dt
else
{:error, _} = err ->
err
end
end
@doc """
Returns a DateTime representing the current moment in time in the local timezone.
## Example
iex> %DateTime{time_zone: tz} = Timex.local();
...> tz != nil
true
"""
@spec local() :: DateTime.t() | {:error, term}
def local() do
with tz when is_binary(tz) <- Timezone.Local.lookup(),
{:ok, datetime} <- DateTime.now(tz, Timex.Timezone.Database) do
datetime
else
{:error, _} = err ->
err
end
end
@doc """
Returns a DateTime representing the given date/time in the local timezone
## Example
iex> %DateTime{time_zone: tz} = Timex.local(DateTime.utc_now());
...> tz != nil
true
"""
@spec local(Types.valid_datetime()) :: DateTime.t() | AmbiguousDateTime.t() | {:error, term}
def local(%DateTime{} = datetime) do
with tz when is_binary(tz) <- Timezone.Local.lookup(),
{:ok, datetime} <- DateTime.shift_zone(datetime, tz, Timex.Timezone.Database) do
datetime
else
{:error, _} = err ->
err
end
end
def local(date) do
with tz when is_binary(tz) <- Timezone.Local.lookup() do
to_datetime(date, tz)
else
{:error, _} = err ->
err
end
end
@doc """
Returns a Date representing the start of the UNIX epoch
"""
@spec epoch() :: Date.t()
def epoch(), do: %Date{year: 1970, month: 1, day: 1}
@doc """
Returns a Date representing the start of the Gregorian epoch
"""
@spec zero() :: Date.t()
def zero(), do: %Date{year: 0, month: 1, day: 1}
@doc """
Convert a date/time value to a Date struct.
"""
@spec to_date(Types.valid_datetime()) :: Date.t() | {:error, term}
defdelegate to_date(date), to: Timex.Protocol
@doc """
Convert a date/time value to a NaiveDateTime struct.
"""
@spec to_naive_datetime(Types.valid_datetime()) :: NaiveDateTime.t() | {:error, term}
defdelegate to_naive_datetime(date), to: Timex.Protocol
@doc """
Convert a date/time value and timezone name to a DateTime struct.
If the DateTime did not occur in the timezone, an error will be returned.
If the DateTime is ambiguous and cannot be resolved, an AmbiguousDateTime will be returned,
allowing the developer to choose which of the two choices is desired.
If no timezone is provided, "Etc/UTC" will be used.
### Examples
iex> Timex.to_datetime(~N[2022-01-01 12:00:00], "America/New_York")
#DateTime<2022-01-01 12:00:00-05:00 EST America/New_York>
# This time was skipped as daylight savings started and clocks moved forward
iex> Timex.to_datetime(~N[2021-03-14 02:30:00], "America/New_York")
{:error, {:could_not_resolve_timezone, "America/New_York", 63782908200, :wall}}
# This time occurred twice as daylight savings ended and clocks moved back
iex> %AmbiguousDateTime{} = adt = Timex.to_datetime(~N[2021-11-07 01:30:00], "America/New_York")
...> match?(%DateTime{zone_abbr: "EDT"}, adt.before) && match?(%DateTime{zone_abbr: "EST"}, adt.after)
true
iex> Timex.to_datetime(~N[2022-01-01 12:00:00])
~U[2022-01-01 12:00:00Z]
"""
@spec to_datetime(Types.valid_datetime()) :: DateTime.t() | {:error, term}
@spec to_datetime(Types.valid_datetime(), Types.valid_timezone()) ::
DateTime.t() | AmbiguousDateTime.t() | {:error, term}
def to_datetime(%DateTime{} = dt), do: dt
def to_datetime(from), do: Timex.Protocol.to_datetime(from, "Etc/UTC")
defdelegate to_datetime(from, timezone), to: Timex.Protocol
@doc """
Convert a date/time value to it's Erlang representation
"""
@spec to_erl(Types.valid_datetime()) :: Types.date() | Types.datetime() | {:error, term}
defdelegate to_erl(date), to: Timex.Protocol
@doc """
Convert a date/time value to a Julian calendar date number
"""
@spec to_julian(Types.valid_datetime()) :: integer | {:error, term}
defdelegate to_julian(datetime), to: Timex.Protocol
@doc """
Convert a date/time value to gregorian seconds (seconds since start of year zero)
"""
@spec to_gregorian_seconds(Types.valid_datetime()) :: non_neg_integer | {:error, term}
defdelegate to_gregorian_seconds(datetime), to: Timex.Protocol
@doc """
Convert a date/time value to gregorian microseconds (microseconds since start of year zero)
"""
@spec to_gregorian_microseconds(Types.valid_datetime()) :: non_neg_integer | {:error, term}
defdelegate to_gregorian_microseconds(datetime), to: Timex.Protocol
@doc """
Convert a date/time value to seconds since the UNIX epoch
"""
@spec to_unix(Types.valid_datetime()) :: non_neg_integer | {:error, term}
defdelegate to_unix(datetime), to: Timex.Protocol
@doc """
Delegates to `DateTime.from_unix!/2`. To recap the docs:
Converts the given Unix time to DateTime.
The integer can be given in different units according to `System.convert_time_unit/3`
and it will be converted to microseconds internally. Defaults to `:second`.
Unix times are always in UTC and therefore the DateTime will be returned in UTC.
"""
@spec from_unix(secs :: non_neg_integer, :native | Types.second_time_units()) ::
DateTime.t() | no_return
def from_unix(secs, unit \\ :second)
def from_unix(secs, :seconds) do
from_unix(secs, :second)
end
def from_unix(secs, :milliseconds) do
from_unix(secs, :millisecond)
end
def from_unix(secs, :microseconds) do
from_unix(secs, :microsecond)
end
def from_unix(secs, :nanoseconds) do
from_unix(secs, :nanosecond)
end
def from_unix(secs, unit) do
DateTime.from_unix!(secs, unit)
end
@doc """
Formats a date/time value using the given format string (and optional formatter).
See `Timex.Format.DateTime.Formatters.Default` or `Timex.Format.DateTime.Formatters.Strftime`
for documentation on the syntax supported by those formatters.
To use the Default formatter, simply call `format/2`. To use the Strftime formatter, you
can either alias and pass Strftime by module name, or as a shortcut, you can pass :strftime
instead.
Formatting will convert other dates than Elixir date types (Date, DateTime, NaiveDateTime)
to a NaiveDateTime using `to_naive_datetime/1` before formatting.
## Examples
iex> date = ~D[2016-02-29]
...> Timex.format(date, "{YYYY}-{0M}-{D}")
{:ok, "2016-02-29"}
iex> datetime = Timex.to_datetime({{2016,2,29},{22,25,0}}, "Etc/UTC")
...> Timex.format(datetime, "{ISO:Extended}")
{:ok, "2016-02-29T22:25:00+00:00"}
"""
@spec format(Types.valid_datetime(), format :: String.t()) :: {:ok, String.t()} | {:error, term}
defdelegate format(datetime, format_string), to: Timex.Format.DateTime.Formatter
@doc """
Same as format/2, except using a custom formatter
## Examples
iex> use Timex
...> datetime = Timex.to_datetime({{2016,2,29},{22,25,0}}, "America/Chicago")
iex> Timex.format(datetime, "%FT%T%:z", :strftime)
{:ok, "2016-02-29T22:25:00-06:00"}
"""
@spec format(Types.valid_datetime(), format :: String.t(), formatter :: atom) ::
{:ok, String.t()} | {:error, term}
defdelegate format(datetime, format_string, formatter), to: Timex.Format.DateTime.Formatter
@doc """
Same as format/2, except takes a locale name to translate text to.
Translations only apply to units, relative time phrases, and only for the locales in the
list of supported locales in the Timex documentation.
"""
@spec lformat(Types.valid_datetime(), format :: String.t(), locale :: String.t()) ::
{:ok, String.t()} | {:error, term}
defdelegate lformat(datetime, format_string, locale), to: Timex.Format.DateTime.Formatter
@doc """
Same as lformat/3, except takes a formatter as it's last argument.
Translations only apply to units, relative time phrases, and only for the locales in the
list of supported locales in the Timex documentation.
"""
@spec lformat(
Types.valid_datetime(),
format :: String.t(),
locale :: String.t(),
formatter :: atom
) :: {:ok, String.t()} | {:error, term}
defdelegate lformat(datetime, format_string, locale, formatter),
to: Timex.Format.DateTime.Formatter
@doc """
Same as format/2, except it returns only the value (not a tuple) and raises on error.
## Examples
iex> date = ~D[2016-02-29]
...> Timex.format!(date, "{YYYY}-{0M}-{D}")
"2016-02-29"
"""
@spec format!(Types.valid_datetime(), format :: String.t()) :: String.t() | no_return
defdelegate format!(datetime, format_string), to: Timex.Format.DateTime.Formatter
@doc """
Same as format/3, except it returns only the value (not a tuple) and raises on error.
## Examples
iex> use Timex
...> datetime = Timex.to_datetime({{2016,2,29},{22,25,0}}, "America/Chicago")
iex> Timex.format!(datetime, "%FT%T%:z", :strftime)
"2016-02-29T22:25:00-06:00"
"""
@spec format!(Types.valid_datetime(), format :: String.t(), formatter :: atom) ::
String.t() | no_return
defdelegate format!(datetime, format_string, formatter), to: Timex.Format.DateTime.Formatter
@doc """
Same as lformat/3, except local_format! raises on error.
See lformat/3 docs for usage examples.
"""
@spec lformat!(Types.valid_datetime(), format :: String.t(), locale :: String.t()) ::
String.t() | no_return
defdelegate lformat!(datetime, format_string, locale), to: Timex.Format.DateTime.Formatter
@doc """
Same as lformat/4, except local_format! raises on error.
See lformat/4 docs for usage examples
"""
@spec lformat!(
Types.valid_datetime(),
format :: String.t(),
locale :: String.t(),
formatter :: atom
) :: String.t() | no_return
defdelegate lformat!(datetime, format_string, locale, formatter),
to: Timex.Format.DateTime.Formatter
@doc """
Formats a DateTime using a fuzzy relative duration, from now.
## Examples
iex> use Timex
...> Timex.from_now(Timex.shift(DateTime.utc_now(), days: 2, hours: 1))
"in 2 days"
iex> use Timex
...> Timex.from_now(Timex.shift(DateTime.utc_now(), days: -2))
"2 days ago"
"""
@spec from_now(Types.valid_datetime()) :: String.t() | {:error, term}
def from_now(datetime), do: from_now(datetime, Timex.Translator.current_locale())
@doc """
Formats a DateTime using a fuzzy relative duration, translated using given locale
## Examples
iex> use Timex
...> Timex.from_now(Timex.shift(DateTime.utc_now(), days: 2, hours: 1), "ru")
"через 2 дня"
iex> use Timex
...> Timex.from_now(Timex.shift(DateTime.utc_now(), days: -2), "ru")
"2 дня назад"
"""
@spec from_now(Types.valid_datetime(), String.t()) :: String.t() | {:error, term}
def from_now(datetime, locale) when is_binary(locale) do
case to_naive_datetime(datetime) do
{:error, _} = err ->
err
%NaiveDateTime{} = dt ->
case lformat(dt, "{relative}", locale, :relative) do
{:ok, formatted} -> formatted
{:error, _} = err -> err
end
end
end
# Formats a DateTime using a fuzzy relative duration, with a reference datetime other than now
@spec from_now(Types.valid_datetime(), Types.valid_datetime()) :: String.t() | {:error, term}
def from_now(datetime, reference_date),
do: from_now(datetime, reference_date, Timex.Translator.current_locale())
@doc """
Formats a DateTime using a fuzzy relative duration, with a reference datetime other than now,
translated using the given locale
"""
@spec from_now(Types.valid_datetime(), Types.valid_datetime(), String.t()) ::
String.t() | {:error, term}
def from_now(datetime, reference_date, locale) when is_binary(locale) do
case to_naive_datetime(datetime) do
{:error, _} = err ->
err
%NaiveDateTime{} = dt ->
case to_naive_datetime(reference_date) do
{:error, _} = err ->
err
%NaiveDateTime{} = ref ->
case Timex.Format.DateTime.Formatters.Relative.relative_to(
dt,
ref,
"{relative}",
locale
) do
{:ok, formatted} -> formatted
{:error, _} = err -> err
end
end
end
end
@doc """
Formats an Erlang timestamp using the ISO-8601 duration format, or optionally, with a custom
formatter of your choosing.
See Timex.Format.Duration.Formatters.Default or Timex.Format.Duration.Formatters.Humanized
for documentation on the specific formatter behaviour.
To use the Default formatter, simply call format_duration/2.
To use the Humanized formatter, you can either alias and pass Humanized by module name,
or as a shortcut, you can pass :humanized instead.
## Examples
iex> use Timex
...> duration = Duration.from_seconds(Timex.to_unix({2016, 2, 29}))
...> Timex.format_duration(duration)
"P46Y2M10D"
iex> use Timex
...> duration = Duration.from_seconds(Timex.to_unix({2016, 2, 29}))
...> Timex.format_duration(duration, :humanized)
"46 years, 2 months, 1 week, 3 days"
iex> use Timex
...> datetime = Duration.from_seconds(Timex.to_unix(~N[2016-02-29T22:25:00]))
...> Timex.format_duration(datetime, :humanized)
"46 years, 2 months, 1 week, 3 days, 22 hours, 25 minutes"
"""
@spec format_duration(Duration.t()) :: String.t() | {:error, term}
defdelegate format_duration(timestamp), to: Timex.Format.Duration.Formatter, as: :format
@doc """
Same as format_duration/1, except it also accepts a formatter
"""
@spec format_duration(Duration.t(), atom) :: String.t() | {:error, term}
defdelegate format_duration(timestamp, formatter),
to: Timex.Format.Duration.Formatter,
as: :format
@doc """
Same as format_duration/1, except takes a locale for use in translation
"""
@spec lformat_duration(Duration.t(), locale :: String.t()) :: String.t() | {:error, term}
defdelegate lformat_duration(timestamp, locale),
to: Timex.Format.Duration.Formatter,
as: :lformat
@doc """
Same as lformat_duration/2, except takes a formatter as an argument
"""
@spec lformat_duration(Duration.t(), locale :: String.t(), atom) :: String.t() | {:error, term}
defdelegate lformat_duration(timestamp, locale, formatter),
to: Timex.Format.Duration.Formatter,
as: :lformat
@doc """
Parses a datetime string into a DateTime struct, using the provided format string (and optional tokenizer).
See `Timex.Format.DateTime.Formatters.Default` or `Timex.Format.DateTime.Formatters.Strftime`
for documentation on the syntax supported in format strings by their respective tokenizers.
To use the Default tokenizer, simply call `parse/2`. To use the Strftime tokenizer, you
can either alias and pass Timex.Parse.DateTime.Tokenizer.Strftime by module name,
or as a shortcut, you can pass :strftime instead.
## Examples
iex> use Timex
...> {:ok, result} = Timex.parse("2016-02-29", "{YYYY}-{0M}-{D}")
...> result
~N[2016-02-29T00:00:00]
iex> use Timex
...> expected = Timex.to_datetime({{2016, 2, 29}, {22, 25, 0}}, "America/Chicago")
...> {:ok, result} = Timex.parse("2016-02-29T22:25:00-06:00", "{ISO:Extended}")
...> Timex.equal?(expected, result)
true
iex> use Timex
...> expected = Timex.to_datetime({{2016, 2, 29}, {22, 25, 0}}, "America/Chicago")
...> {:ok, result} = Timex.parse("2016-02-29T22:25:00-06:00", "%FT%T%:z", :strftime)
...> Timex.equal?(expected, result)
true
"""
@spec parse(String.t(), String.t()) ::
{:ok, DateTime.t() | NaiveDateTime.t() | AmbiguousDateTime.t()} | {:error, term}
@spec parse(String.t(), String.t(), atom) ::
{:ok, DateTime.t() | NaiveDateTime.t() | AmbiguousDateTime.t()} | {:error, term}
defdelegate parse(datetime_string, format_string), to: Timex.Parse.DateTime.Parser
defdelegate parse(datetime_string, format_string, tokenizer), to: Timex.Parse.DateTime.Parser
@doc """
Same as parse/2 and parse/3, except parse! raises on error.
See parse/2 or parse/3 docs for usage examples.
"""
@spec parse!(String.t(), String.t()) ::
DateTime.t() | NaiveDateTime.t() | AmbiguousDateTime.t() | no_return
@spec parse!(String.t(), String.t(), atom) ::
DateTime.t() | NaiveDateTime.t() | AmbiguousDateTime.t() | no_return
defdelegate parse!(datetime_string, format_string), to: Timex.Parse.DateTime.Parser
defdelegate parse!(datetime_string, format_string, tokenizer), to: Timex.Parse.DateTime.Parser
@doc """
Given a format string, validates that the format string is valid for the Default formatter.
Given a format string and a formatter, validates that the format string is valid for that formatter.
## Examples
iex> use Timex
...> Timex.validate_format("{YYYY}-{M}-{D}")
:ok
iex> use Timex
...> Timex.validate_format("{YYYY}-{M}-{V}")
{:error, "Expected end of input at line 1, column 11"}
iex> use Timex
...> Timex.validate_format("%FT%T%:z", :strftime)
:ok
"""
@spec validate_format(String.t()) :: :ok | {:error, term}
@spec validate_format(String.t(), atom) :: :ok | {:error, term}
defdelegate validate_format(format_string), to: Timex.Format.DateTime.Formatter, as: :validate
defdelegate validate_format(format_string, formatter),
to: Timex.Format.DateTime.Formatter,
as: :validate
@doc """
Gets the current century
## Examples
iex> Timex.century
21
"""
@spec century() :: non_neg_integer | {:error, term}
def century(), do: century(:calendar.universal_time())
@doc """
Given a date, get the century this date is in.
## Examples
iex> Timex.today |> Timex.century
21
iex> Timex.now |> Timex.century
21
iex> Timex.century(2016)
21
"""
@spec century(Types.year() | Types.valid_datetime()) :: non_neg_integer | {:error, term}
def century(year) when is_integer(year) do
base_century = div(year, 100)
years_past = rem(year, 100)
cond do
base_century == base_century - years_past -> base_century
true -> base_century + 1
end
end
def century(date), do: Timex.Protocol.century(date)
@doc """
Convert an iso ordinal day number to the day it represents in the current year.
## Examples
iex> %Date{:year => year} = Timex.from_iso_day(180)
...> %Date{:year => todays_year} = Timex.today()
...> year == todays_year
true
"""
@spec from_iso_day(non_neg_integer) :: Date.t() | {:error, term}
def from_iso_day(day) when is_day_of_year(day) do
{{year, _, _}, _} = :calendar.universal_time()
from_iso_day(day, year)
end
def from_iso_day(_), do: {:error, {:from_iso_day, :invalid_iso_day}}
@doc """
Same as from_iso_day/1, except you can expect the following based on the second parameter:
- If an integer year is given, the result will be a Date struct
- For any date/time value, the result will be in the same format (i.e. Date -> Date)
In all cases, the resulting value will be the date representation of the provided ISO day in that year
## Examples
### Creating a Date from the given day
iex> use Timex
...> expected = ~D[2015-06-29]
...> (expected === Timex.from_iso_day(180, 2015))
true
### Creating a Date/DateTime from the given day
iex> use Timex
...> expected = Timex.to_datetime({{2015, 6, 29}, {0,0,0}}, "Etc/UTC")
...> beginning = Timex.to_datetime({{2015,1,1}, {0,0,0}}, "Etc/UTC")
...> (expected === Timex.from_iso_day(180, beginning))
true
### Shifting a Date/DateTime to the given day
iex> use Timex
...> date = Timex.to_datetime({{2015,6,26}, {12,0,0}}, "Etc/UTC")
...> expected = Timex.to_datetime({{2015, 6, 29}, {12,0,0}}, "Etc/UTC")
...> (Timex.from_iso_day(180, date) === expected)
true
"""
@spec from_iso_day(non_neg_integer, Types.year() | Types.valid_datetime()) ::
Types.valid_datetime() | {:error, term}
def from_iso_day(day, year) when is_day_of_year(day) and is_year(year) do
{year, month, day} = Helpers.iso_day_to_date_tuple(year, day)
%Date{year: year, month: month, day: day}
end
def from_iso_day(day, datetime), do: Timex.Protocol.from_iso_day(datetime, day)
@doc """
Return a pair {year, week number} (as defined by ISO 8601) that the given
Date/DateTime value falls on.
## Examples
iex> Timex.iso_week({1970, 1, 1})
{1970,1}
"""
@spec iso_week(Types.valid_datetime()) :: {Types.year(), Types.weeknum()} | {:error, term}
defdelegate iso_week(datetime), to: Timex.Protocol
@doc """
Same as iso_week/1, except this takes a year, month, and day as distinct arguments.
## Examples
iex> Timex.iso_week(1970, 1, 1)
{1970,1}
"""
@spec iso_week(Types.year(), Types.month(), Types.day()) ::
{Types.year(), Types.weeknum()} | {:error, term}
def iso_week(year, month, day) when is_date(year, month, day),
do: :calendar.iso_week_number({year, month, day})
def iso_week(_, _, _),
do: {:error, {:iso_week, :invalid_date}}
@doc """
Return a 3-tuple {year, week number, weekday} for the given Date/DateTime.
## Examples
iex> Timex.iso_triplet(Timex.epoch)
{1970, 1, 4}
"""
@spec iso_triplet(Types.valid_datetime()) ::
{Types.year(), Types.weeknum(), Types.weekday()} | {:error, term}
def iso_triplet(datetime) do
case to_erl(datetime) do
{:error, _} = err ->
err
{y, m, d} = date ->
{iso_year, iso_week} = iso_week(y, m, d)
{iso_year, iso_week, Timex.weekday(date)}
{{y, m, d} = date, _} ->
{iso_year, iso_week} = iso_week(y, m, d)
{iso_year, iso_week, Timex.weekday(date)}
end
end
@doc """
Given an ISO triplet `{year, week number, weekday}`, convert it to a Date struct.
## Examples
iex> expected = Timex.to_date({2014, 1, 28})
iex> Timex.from_iso_triplet({2014, 5, 2}) === expected
true
"""
@spec from_iso_triplet(Types.iso_triplet()) :: Date.t() | {:error, term}
def from_iso_triplet({year, week, weekday})
when is_year(year) and is_week_of_year(week) and is_day_of_week(weekday, :mon) do
{_, _, jan4weekday} = iso_triplet({year, 1, 4})
offset = jan4weekday + 3
ordinal_day = week * 7 + weekday - offset
{year, iso_day} =
case {year, ordinal_day} do
{year, ordinal_day} when ordinal_day < 1 and is_leap_year(year - 1) ->
{year - 1, ordinal_day + 366}
{year, ordinal_day} when ordinal_day < 1 ->
{year - 1, ordinal_day + 365}
{year, ordinal_day} when ordinal_day > 366 and is_leap_year(year) ->
{year + 1, ordinal_day - 366}
{year, ordinal_day} when ordinal_day > 365 and not is_leap_year(year) ->
{year + 1, ordinal_day - 365}
_ ->
{year, ordinal_day}
end
{year, month, day} = Helpers.iso_day_to_date_tuple(year, iso_day)
%Date{year: year, month: month, day: day}
end
def from_iso_triplet({_, _, _}), do: {:error, {:from_iso_triplet, :invalid_triplet}}
@doc """
Returns a list of all valid timezone names in the Olson database
"""
@spec timezones() :: [String.t()]
def timezones(), do: Tzdata.zone_list()
@doc """
Get a TimezoneInfo object for the specified offset or name.
When offset or name is invalid, exception is raised.
If no DateTime value is given for the second parameter, the current date/time
will be used (in other words, it will return the current timezone info for the
given zone). If one is provided, the timezone info returned will be based on
the provided DateTime (or Erlang datetime tuple) value.
## Examples
iex> date = Timex.to_datetime({2015, 4, 12})
...> tz = Timex.timezone(:utc, date)
...> tz.full_name
"Etc/UTC"
iex> tz = Timex.timezone("America/Chicago", {2015,4,12})
...> {tz.full_name, tz.abbreviation}
{"America/Chicago", "CDT"}
iex> tz = Timex.timezone(+2, {2015, 4, 12})
...> {tz.full_name, tz.abbreviation}
{"Etc/UTC+2", "+02"}
"""
@spec timezone(Types.valid_timezone() | TimezoneInfo.t(), Types.valid_datetime()) ::
TimezoneInfo.t() | AmbiguousTimezoneInfo.t() | {:error, term}
def timezone(tz, datetime), do: Timezone.get(tz, datetime)
@doc """
Return a boolean indicating whether the given date is valid.
## Examples
iex> use Timex
...> Timex.is_valid?(~N[0001-01-01T01:01:01])
true
iex> use Timex
...> %Date{year: 1, day: 1, month: 13} |> Timex.is_valid?
false
"""
@spec is_valid?(Types.valid_datetime()) :: boolean
def is_valid?(datetime) do
case Timex.Protocol.is_valid?(datetime) do
{:error, _reason} ->
false
b when is_boolean(b) ->
b
end
end
@doc """
Returns a boolean indicating whether the provided term represents a valid time,
valid times are one of:
- `{hour, min, sec}`
- `{hour, min, sec, ms}`
"""
@spec is_valid_time?(term) :: boolean
def is_valid_time?({hour, min, sec}) when is_time(hour, min, sec), do: true
def is_valid_time?({hour, min, sec, ms}) when is_time(hour, min, sec, ms), do: true
def is_valid_time?(_), do: false
@doc """
Returns a boolean indicating whether the provided term represents a valid timezone,
valid timezones are one of:
- TimezoneInfo struct
- A timezone name as a string
- `:utc` as a shortcut for the UTC timezone
- `:local` as a shortcut for the local timezone
- A number representing an offset from UTC
"""
@spec is_valid_timezone?(term) :: boolean
def is_valid_timezone?(timezone) do
case Timezone.name_of(timezone) do
{:error, _} -> false
_name -> true
end
end
@doc """
Returns a boolean indicating whether the first `Timex.Comparable` occurs before the second
"""
@spec before?(Time.t() | Comparable.comparable(), Time.t() | Comparable.comparable()) :: boolean
def before?(a, b) do
case compare(a, b) do
{:error, reason} ->
raise ArgumentError, message: "#{inspect(reason)}"
-1 ->
true
_ ->
false
end
end
@doc """
Returns a boolean indicating whether the first `Timex.Comparable` occurs after the second
"""
@spec after?(Time.t() | Comparable.comparable(), Time.t() | Comparable.comparable()) :: boolean
def after?(a, b) do
case compare(a, b) do
{:error, reason} ->
raise ArgumentError, message: "#{inspect(reason)}"
1 ->
true
_ ->
false
end
end
@doc """
Returns a boolean indicating whether the first `Timex.Comparable` occurs between the second
and third.
If an error occurs, an error tuple will be returned.
By default, the `start` and `end` bounds are *exclusive*. You can opt for inclusive bounds with the
`inclusive: true` option.
To set just one of the bounds as inclusive, use the
`inclusive: :start` or `inclusive: :end` option.
Also, by default, for `Time.t`, if `start` and `end`
are on different sides of midnight,
it doesn't count as a continous period. Hence, `23:00 < 00:00, 01:00` would return `false`.
To use cycled time, use option `cycled: true`.
"""
@type between_options :: [
inclusive:
boolean
| :start
| :end,
cycled: boolean
]
@spec between?(
Time.t() | Comparable.comparable(),
Time.t() | Comparable.comparable(),
Time.t() | Comparable.comparable(),
between_options
) :: boolean
def between?(a, start, ending, options \\ []) do
{start_test, ending_test} =
case Keyword.get(options, :inclusive, false) do
:start -> {0, 1}
:end -> {1, 0}
true -> {0, 0}
_ -> {1, 1}
end
passes_midnight? =
case Keyword.get(options, :cycled, false) do
true ->
case {a, start, ending} do
{%Time{}, %Time{}, %Time{}} ->
between?(ending, ~T[00:00:00], start, inclusive: :start)
_ ->
raise ArgumentError,
message:
"cycled: true was passed, but one of arguments is not Time.t: #{inspect({a, start, ending})}"
end
false ->
false
end
in_bounds?(compare(a, start), compare(ending, a), start_test, ending_test, passes_midnight?)
end
defp in_bounds?({:error, reason}, _, _, _, _),
do: raise(ArgumentError, message: "#{inspect(reason)}")
defp in_bounds?(_, {:error, reason}, _, _, _),
do: raise(ArgumentError, message: "#{inspect(reason)}")
defp in_bounds?(start_comparison, ending_comparison, start_test, ending_test, passes_midnight?) do
after_start? = start_comparison >= start_test
before_end? = ending_comparison >= ending_test
if passes_midnight? do
after_start? || before_end?
else
after_start? && before_end?
end
end
@doc """
Returns a boolean indicating whether the two `Timex.Comparable` values are equivalent.
Equality here implies that the two Comparables represent the same moment in time (with
the given granularity), not equality of the data structure.
The options for granularity is the same as for `compare/3`, defaults to `:seconds`.
## Examples
iex> date1 = ~D[2014-03-01]
...> date2 = ~D[2014-03-01]
...> Timex.equal?(date1, date2)
true
iex> date1 = ~D[2014-03-01]
...> date2 = Timex.to_datetime({2014, 3, 1}, "Etc/UTC")
...> Timex.equal?(date1, date2)
true
"""
@spec equal?(
Time.t() | Comparable.comparable(),
Time.t() | Comparable.comparable(),
Comparable.granularity()
) ::
boolean | no_return
def equal?(a, a, granularity \\ :seconds)
def equal?(a, a, _granularity), do: true