-
Notifications
You must be signed in to change notification settings - Fork 9
/
time.gleam
1105 lines (991 loc) · 28.2 KB
/
time.gleam
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
import gleam/int
import gleam/bool
import gleam/list
import gleam/order
import gleam/regex
import gleam/result
import gleam/string
import gleam/option
import gleam/function
import gleam/iterator
import birl/duration
import birl/zones
import ranger
pub opaque type DateTime {
DateTime(
wall_time: Int,
offset: Int,
timezone: option.Option(String),
monotonic_time: option.Option(Int),
)
}
pub type Date {
Date(year: Int, month: Int, day: Int)
}
pub type Time {
Time(hour: Int, minute: Int, second: Int, milli_second: Int)
}
/// starting point of unix timestamps
pub const unix_epoch = DateTime(0, 0, option.None, option.None)
pub type Weekday {
Mon
Tue
Wed
Thu
Fri
Sat
Sun
}
pub type Month {
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
}
/// use this to get the current time in the local timezone offset
pub fn now() -> DateTime {
let now = ffi_now()
let offset_in_minutes = ffi_local_offset()
let monotonic_now = ffi_monotonic_now()
let timezone = local_timezone()
DateTime(
now,
offset_in_minutes * 60_000_000,
option.map(
timezone,
fn(tz) {
case
zones.list
|> list.any(fn(item) { item.0 == tz })
{
True -> option.Some(tz)
False -> option.None
}
},
)
|> option.flatten,
option.Some(monotonic_now),
)
}
/// use this to get the current time in utc
pub fn utc_now() -> DateTime {
let now = ffi_now()
let monotonic_now = ffi_monotonic_now()
DateTime(now, 0, option.Some("Etc/UTC"), option.Some(monotonic_now))
}
/// use this to get the current time with a given offset.
///
/// Some examples of acceptable offsets:
///
/// `"+330", "03:30", "-8:00","-7", "-0400", "03"`
pub fn now_with_offset(offset: String) -> Result(DateTime, Nil) {
use offset <- result.then(parse_offset(offset))
let now = ffi_now()
let monotonic_now = ffi_monotonic_now()
DateTime(now, offset, option.None, option.Some(monotonic_now))
|> Ok
}
pub fn now_with_timezone(timezone: String) -> Result(DateTime, Nil) {
case
zones.list
|> list.key_find(timezone)
{
Ok(offset) -> {
let now = ffi_now()
let monotonic_now = ffi_monotonic_now()
DateTime(
now,
offset * 1_000_000,
option.Some(timezone),
option.Some(monotonic_now),
)
|> Ok
}
Error(Nil) -> Error(Nil)
}
}
pub fn monotonic_now() -> Int {
ffi_monotonic_now()
}
pub fn to_iso8601(value: DateTime) -> String {
let #(#(year, month, day), #(hour, minute, second, milli_second), offset) =
to_parts(value)
int.to_string(year) <> "-" <> {
month
|> int.to_string
|> string.pad_left(2, "0")
} <> "-" <> {
day
|> int.to_string
|> string.pad_left(2, "0")
} <> "T" <> {
hour
|> int.to_string
|> string.pad_left(2, "0")
} <> ":" <> {
minute
|> int.to_string
|> string.pad_left(2, "0")
} <> ":" <> {
second
|> int.to_string
|> string.pad_left(2, "0")
} <> "." <> {
milli_second
|> int.to_string
|> string.pad_left(3, "0")
} <> offset
}
pub fn from_iso8601(value: String) -> Result(DateTime, Nil) {
let assert Ok(offset_pattern) = regex.from_string("(.*)([+|\\-].*)")
let value = string.trim(value)
let #(date_string, offsetted_time_string) = case string.split(value, "T") {
[date_string] -> #(date_string, "00")
[date_string, offsetted_time_string] -> #(
date_string,
offsetted_time_string,
)
}
let date_string = string.trim(date_string)
let offsetted_time_string = string.trim(offsetted_time_string)
let #(time_string, offset_string) = case
string.ends_with(offsetted_time_string, "Z") || string.ends_with(
offsetted_time_string,
"z",
)
{
True -> #(string.drop_right(offsetted_time_string, 1), "+00:00")
False ->
case regex.scan(offset_pattern, offsetted_time_string) {
[regex.Match(_, [option.Some(time_string), option.Some(offset_string)])] -> #(
time_string,
offset_string,
)
[] -> {
let local_offset_in_minutes = ffi_local_offset()
let assert Ok(local_offset_string) =
generate_offset(local_offset_in_minutes * 60_000_000)
#(offsetted_time_string, local_offset_string)
}
}
}
let time_string = string.replace(time_string, ":", "")
let #(time_string, milli_seconds_result) = case
string.split(time_string, ".")
{
[time_string] -> #(time_string, Ok(0))
[time_string, milli_seconds_string] -> #(
time_string,
int.parse(milli_seconds_string),
)
}
case milli_seconds_result {
Ok(milli_seconds) -> {
use [year, month, day] <- result.then(parse_date(date_string))
use [hour, minute, second] <- result.then(parse_time(time_string))
case
from_parts(
#(year, month, day),
#(hour, minute, second, milli_seconds),
offset_string,
)
{
Ok(DateTime(timestamp, offset, option.None, option.None)) ->
Ok(DateTime(timestamp, offset, option.None, option.None))
Error(Nil) -> Error(Nil)
}
}
Error(Nil) -> Error(Nil)
}
}
/// the naive format is the same as ISO8601 except that it does not contain the offset
pub fn to_naive(value: DateTime) -> String {
let #(#(year, month, day), #(hour, minute, second, milli_second), _) =
to_parts(value)
int.to_string(year) <> "-" <> {
month
|> int.to_string
|> string.pad_left(2, "0")
} <> "-" <> {
day
|> int.to_string
|> string.pad_left(2, "0")
} <> "T" <> {
hour
|> int.to_string
|> string.pad_left(2, "0")
} <> ":" <> {
minute
|> int.to_string
|> string.pad_left(2, "0")
} <> ":" <> {
second
|> int.to_string
|> string.pad_left(2, "0")
} <> "." <> {
milli_second
|> int.to_string
|> string.pad_left(3, "0")
}
}
/// the naive format is the same as ISO8601 except that it does not contain the offset
pub fn from_naive(value: String) -> Result(DateTime, Nil) {
let value = string.trim(value)
let #(date_string, time_string) = case string.split(value, "T") {
[date_string] -> #(date_string, "00")
[date_string, time_string] -> #(date_string, time_string)
}
let date_string = string.trim(date_string)
let time_string = string.trim(time_string)
let time_string = string.replace(time_string, ":", "")
let #(time_string, milli_seconds_result) = case
string.split(time_string, ".")
{
[time_string] -> #(time_string, Ok(0))
[time_string, milli_seconds_string] -> #(
time_string,
int.parse(milli_seconds_string),
)
}
case milli_seconds_result {
Ok(milli_seconds) -> {
use [year, month, day] <- result.then(parse_date(date_string))
use [hour, minute, second] <- result.then(parse_time(time_string))
case
from_parts(
#(year, month, day),
#(hour, minute, second, milli_seconds),
"Z",
)
{
Ok(DateTime(timestamp, offset, option.None, option.None)) ->
Ok(DateTime(timestamp, offset, option.None, option.None))
Error(Nil) -> Error(Nil)
}
}
Error(Nil) -> Error(Nil)
}
}
/// see [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Date)
pub fn to_http(value: DateTime) -> String {
let assert Ok(value) = set_offset(value, "Z")
let #(#(year, _, day), #(hour, minute, second, _), _) = to_parts(value)
let short_weekday = short_string_weekday(value)
let short_month = short_string_month(value)
short_weekday <> ", " <> {
day
|> int.to_string
|> string.pad_left(2, "0")
} <> " " <> short_month <> " " <> int.to_string(year) <> " " <> {
hour
|> int.to_string
|> string.pad_left(2, "0")
} <> ":" <> {
minute
|> int.to_string
|> string.pad_left(2, "0")
} <> ":" <> {
second
|> int.to_string
|> string.pad_left(2, "0")
} <> " GMT"
}
/// like `to_http` but assumes the offset in the DateTime value instead of `GMT`
pub fn to_http_with_offset(value: DateTime) -> String {
let #(#(year, _, day), #(hour, minute, second, _), offset) = to_parts(value)
let short_weekday = short_string_weekday(value)
let short_month = short_string_month(value)
let offset = case offset {
"Z" -> "GMT"
_ -> offset
}
short_weekday <> ", " <> {
day
|> int.to_string
|> string.pad_left(2, "0")
} <> " " <> short_month <> " " <> int.to_string(year) <> " " <> {
hour
|> int.to_string
|> string.pad_left(2, "0")
} <> ":" <> {
minute
|> int.to_string
|> string.pad_left(2, "0")
} <> ":" <> {
second
|> int.to_string
|> string.pad_left(2, "0")
} <> " " <> offset
}
/// see [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Date)
///
/// also supports other similar formats:
///
/// `Tue, 01-Nov-2016 08:49:37 GMT`
///
/// `Tue, 01 Nov 2016 08:49:37 +0630`
///
/// `Tue, 01-November-2016 08:49:37 Z`
///
/// `Tuesday, 01-Nov-2016 08:49:37 +330`
///
/// `Tuesday, 01 November 2016 08:49:37 +06:30`
pub fn from_http(value: String) -> Result(DateTime, Nil) {
let value = string.trim(value)
let [weekday, rest] = string.split(value, ",")
use <- bool.guard(
!list.any(
weekday_strings,
fn(weekday_item) {
let strings = weekday_item.1
strings.0 == weekday || strings.1 == weekday
},
),
Error(Nil),
)
let rest = string.trim(rest)
let assert Ok(whitespace_pattern) = regex.from_string("\\s+")
case regex.split(whitespace_pattern, rest) {
[day_string, month_string, year_string, time_string, offset_string] -> {
let time_string = string.replace(time_string, ":", "")
case
#(
int.parse(day_string),
month_strings
|> list.index_map(fn(index, month) {
let strings = month.1
#(index, strings.0, strings.1)
})
|> list.find(fn(month) {
month.1 == month_string || month.2 == month_string
}),
int.parse(year_string),
parse_time(time_string),
)
{
#(
Ok(day),
Ok(#(month_index, _, _)),
Ok(year),
Ok([hour, minute, second]),
) ->
case
from_parts(
#(year, month_index + 1, day),
#(hour, minute, second, 0),
case offset_string {
"GMT" -> "Z"
_ -> offset_string
},
)
{
Ok(value) -> {
let correct_weekday = string_weekday(value)
let correct_short_weekday = short_string_weekday(value)
case
list.contains([correct_weekday, correct_short_weekday], weekday)
{
True -> Ok(value)
False -> Error(Nil)
}
}
Error(Nil) -> Error(Nil)
}
_ -> Error(Nil)
}
}
[date_string, time_string, offset_string] ->
case string.split(date_string, "-") {
[day_string, month_string, year_string] -> {
let time_string = string.replace(time_string, ":", "")
case
#(
int.parse(day_string),
month_strings
|> list.index_map(fn(index, month) {
let strings = month.1
#(index, strings.0, strings.1)
})
|> list.find(fn(month) {
month.1 == month_string || month.2 == month_string
}),
int.parse(year_string),
parse_time(time_string),
)
{
#(
Ok(day),
Ok(#(month_index, _, _)),
Ok(year),
Ok([hour, minute, second]),
) ->
case
from_parts(
#(year, month_index + 1, day),
#(hour, minute, second, 0),
case offset_string {
"GMT" -> "Z"
_ -> offset_string
},
)
{
Ok(value) -> {
let correct_weekday = string_weekday(value)
let correct_short_weekday = short_string_weekday(value)
case
list.contains(
[correct_weekday, correct_short_weekday],
weekday,
)
{
True -> Ok(value)
False -> Error(Nil)
}
}
Error(Nil) -> Error(Nil)
}
_ -> Error(Nil)
}
}
_ -> Error(Nil)
}
_ -> Error(Nil)
}
}
/// unix timestamps are the number of seconds that have elapsed since 00:00:00 UTC on January 1st, 1970
pub fn to_unix(value: DateTime) -> Int {
case value {
DateTime(t, _, _, _) -> t / 1_000_000
}
}
/// unix timestamps are the number of seconds that have elapsed since 00:00:00 UTC on January 1st, 1970
pub fn from_unix(value: Int) -> DateTime {
DateTime(value * 1_000_000, 0, option.None, option.None)
}
pub fn compare(a: DateTime, b: DateTime) -> order.Order {
let DateTime(wall_time: wta, offset: _, timezone: _, monotonic_time: mta) = a
let DateTime(wall_time: wtb, offset: _, timezone: _, monotonic_time: mtb) = b
let #(ta, tb) = case #(mta, mtb) {
#(option.Some(ta), option.Some(tb)) -> #(ta, tb)
_ -> #(wta, wtb)
}
case ta == tb {
True -> order.Eq
False ->
case ta < tb {
True -> order.Lt
False -> order.Gt
}
}
}
pub fn difference(a: DateTime, b: DateTime) -> duration.Duration {
let DateTime(wall_time: wta, offset: _, timezone: _, monotonic_time: mta) = a
let DateTime(wall_time: wtb, offset: _, timezone: _, monotonic_time: mtb) = b
let #(ta, tb) = case #(mta, mtb) {
#(option.Some(ta), option.Some(tb)) -> #(ta, tb)
_ -> #(wta, wtb)
}
duration.Duration(ta - tb)
}
const units = [
#(duration.Year, "year"),
#(duration.Month, "month"),
#(duration.Week, "week"),
#(duration.Day, "day"),
#(duration.Hour, "hour"),
#(duration.Minute, "minute"),
#(duration.Second, "second"),
]
pub fn legible_difference(a: DateTime, b: DateTime) -> String {
case
difference(a, b)
|> duration.blur
{
#(_, duration.MicroSecond) | #(_, duration.MilliSecond) -> "just now"
#(amount, unit) -> {
let assert Ok(unit) = list.key_find(units, unit)
let is_negative = amount < 0
let amount = int.absolute_value(amount)
let unit = case amount {
1 -> unit
_ -> unit <> "s"
}
case is_negative {
True -> "in " <> int.to_string(amount) <> " " <> unit
False ->
amount
|> int.absolute_value
|> int.to_string <> " " <> unit <> " ago"
}
}
}
}
pub fn add(value: DateTime, duration: duration.Duration) -> DateTime {
let DateTime(wall_time: wt, offset: o, timezone: timezone, monotonic_time: mt) =
value
let duration.Duration(duration) = duration
case mt {
option.Some(mt) ->
DateTime(
wall_time: wt + duration,
offset: o,
timezone: timezone,
monotonic_time: option.Some(mt + duration),
)
option.None ->
DateTime(
wall_time: wt + duration,
offset: o,
timezone: timezone,
monotonic_time: option.None,
)
}
}
pub fn subtract(value: DateTime, duration: duration.Duration) -> DateTime {
let DateTime(wall_time: wt, offset: o, timezone: timezone, monotonic_time: mt) =
value
let duration.Duration(duration) = duration
case mt {
option.Some(mt) ->
DateTime(
wall_time: wt - duration,
offset: o,
timezone: timezone,
monotonic_time: option.Some(mt - duration),
)
option.None ->
DateTime(
wall_time: wt - duration,
offset: o,
timezone: timezone,
monotonic_time: option.None,
)
}
}
pub fn weekday(value: DateTime) -> Weekday {
case value {
DateTime(wall_time: t, offset: o, timezone: _, monotonic_time: _) -> {
let assert Ok(weekday) = list.at(weekdays, ffi_weekday(t, o))
weekday
}
}
}
pub fn string_weekday(value: DateTime) -> String {
let weekday = weekday(value)
let assert Ok(#(weekday, _)) = list.key_find(weekday_strings, weekday)
weekday
}
pub fn short_string_weekday(value: DateTime) -> String {
let weekday = weekday(value)
let assert Ok(#(_, weekday)) = list.key_find(weekday_strings, weekday)
weekday
}
pub fn month(value: DateTime) -> Month {
let #(#(_, month, _), _, _) = to_parts(value)
let assert Ok(month) = list.at(months, month - 1)
month
}
pub fn string_month(value: DateTime) -> String {
let month = month(value)
let assert Ok(#(month, _)) = list.key_find(month_strings, month)
month
}
pub fn short_string_month(value: DateTime) -> String {
let month = month(value)
let assert Ok(#(_, month)) = list.key_find(month_strings, month)
month
}
/// can be used to create a time range starting from time `a` with step `s`
///
/// if `b` is `option.None` the range will be infinite
pub fn range(
from a: DateTime,
to b: option.Option(DateTime),
step s: duration.Duration,
) -> iterator.Iterator(DateTime) {
let assert Ok(range) = case b {
option.Some(b) ->
ranger.create(
validate: fn(_) { True },
negate_step: fn(duration) {
let duration.Duration(value) = duration
duration.Duration(-1 * value)
},
add: add,
compare: compare,
)(a, b, s)
option.None ->
ranger.create_infinite(
validate: fn(_) { True },
add: add,
compare: compare,
)(a, s)
}
range
|> ranger.unwrap
}
pub fn set_timezone(
value: DateTime,
new_timezone: String,
) -> Result(DateTime, Nil) {
case
zones.list
|> list.key_find(new_timezone)
{
Ok(new_offset_number) -> {
case value {
DateTime(wall_time: t, offset: _, timezone: _, monotonic_time: mt) ->
DateTime(
t,
new_offset_number * 1_000_000,
option.Some(new_timezone),
mt,
)
|> Ok
}
}
Error(Nil) -> Error(Nil)
}
}
pub fn get_timezone(value: DateTime) -> option.Option(String) {
let DateTime(_, _, timezone, _) = value
timezone
}
/// use this to change the offset of a given time value.
///
/// Some examples of acceptable offsets:
///
/// `"+330", "03:30", "-8:00","-7", "-0400", "03", "Z"`
pub fn set_offset(value: DateTime, new_offset: String) -> Result(DateTime, Nil) {
use new_offset_number <- result.then(parse_offset(new_offset))
case value {
DateTime(wall_time: t, offset: _, timezone: timezone, monotonic_time: mt) ->
DateTime(t, new_offset_number, timezone, mt)
|> Ok
}
}
pub fn get_offset(value: DateTime) -> String {
let DateTime(_, offset, _, _) = value
let assert Ok(offset) = generate_offset(offset)
offset
}
pub fn set_date(value: DateTime, date: Date) -> DateTime {
let #(_, time, offset) = to_parts(value)
let Date(year, month, day) = date
let assert Ok(new_value) = from_parts(#(year, month, day), time, offset)
new_value
}
pub fn get_date(value: DateTime) -> Date {
let #(#(year, month, day), _, _) = to_parts(value)
Date(year, month, day)
}
pub fn set_time(value: DateTime, time: Time) -> DateTime {
let #(date, _, offset) = to_parts(value)
let Time(hour, minute, second, milli_second) = time
let assert Ok(new_value) =
from_parts(date, #(hour, minute, second, milli_second), offset)
new_value
}
pub fn get_time(value: DateTime) -> Time {
let #(_, #(hour, minute, second, milli_second), _) = to_parts(value)
Time(hour, minute, second, milli_second)
}
@target(erlang)
/// calculates erlang datetime using the offset in the DateTime value
pub fn to_erlang_datetime(
value: DateTime,
) -> #(#(Int, Int, Int), #(Int, Int, Int)) {
let #(date, #(hour, minute, second, _), _) = to_parts(value)
#(date, #(hour, minute, second))
}
@target(erlang)
/// calculates the universal erlang datetime regardless of the offset in the DateTime value
pub fn to_erlang_universal_datetime(
value: DateTime,
) -> #(#(Int, Int, Int), #(Int, Int, Int)) {
let assert Ok(value) = set_offset(value, "Z")
let #(date, #(hour, minute, second, _), _) = to_parts(value)
#(date, #(hour, minute, second))
}
@target(erlang)
/// calculates the DateTime value from the erlang datetime using the local offset of the system
pub fn from_erlang_local_datetime(
erlang_datetime: #(#(Int, Int, Int), #(Int, Int, Int)),
) -> DateTime {
let #(date, time) = erlang_datetime
let offset_in_minutes = ffi_local_offset()
let DateTime(wall_time, _, option.None, option.None) =
unix_epoch
|> set_date(Date(date.0, date.1, date.2))
|> set_time(Time(time.0, time.1, time.2, 0))
let timezone = local_timezone()
DateTime(
wall_time,
offset_in_minutes * 60_000_000,
option.map(
timezone,
fn(tz) {
case
zones.list
|> list.any(fn(item) { item.0 == tz })
{
True -> option.Some(tz)
False -> option.None
}
},
)
|> option.flatten,
option.None,
)
}
@target(erlang)
/// calculates the DateTime value from the erlang datetime in UTC
pub fn from_erlang_universal_datetime(
erlang_datetime: #(#(Int, Int, Int), #(Int, Int, Int)),
) -> DateTime {
let #(date, time) = erlang_datetime
let assert Ok(new_value) =
unix_epoch
|> set_date(Date(date.0, date.1, date.2))
|> set_time(Time(time.0, time.1, time.2, 0))
|> set_timezone("Etc/UTC")
new_value
}
fn to_parts(
value: DateTime,
) -> #(#(Int, Int, Int), #(Int, Int, Int, Int), String) {
case value {
DateTime(wall_time: t, offset: o, timezone: _, monotonic_time: _) -> {
let #(date, time) = ffi_to_parts(t, o)
let assert Ok(offset) = generate_offset(o)
#(date, time, offset)
}
}
}
fn from_parts(
date: #(Int, Int, Int),
time: #(Int, Int, Int, Int),
offset: String,
) -> Result(DateTime, Nil) {
use offset_number <- result.then(parse_offset(offset))
ffi_from_parts(#(date, time), offset_number)
|> DateTime(offset_number, option.None, option.None)
|> Ok
}
fn parse_offset(offset: String) -> Result(Int, Nil) {
use <- bool.guard(list.contains(["Z", "z"], offset), Ok(0))
let assert Ok(re) = regex.from_string("([+-])")
use #(sign, offset) <- result.then(case regex.split(re, offset) {
["", "+", offset] -> Ok(#(1, offset))
["", "-", offset] -> Ok(#(-1, offset))
[_] -> Ok(#(1, offset))
_ -> Error(Nil)
})
case string.split(offset, ":") {
[hour_str, minute_str] -> {
use hour <- result.then(int.parse(hour_str))
use minute <- result.then(int.parse(minute_str))
Ok(sign * { hour * 60 + minute } * 60 * 1_000_000)
}
[offset] ->
case string.length(offset) {
1 | 2 -> {
use hour <- result.then(int.parse(offset))
Ok(sign * hour * 3600 * 1_000_000)
}
3 -> {
let assert Ok(hour_str) = string.first(offset)
let minute_str = string.slice(offset, 1, 2)
use hour <- result.then(int.parse(hour_str))
use minute <- result.then(int.parse(minute_str))
Ok(sign * { hour * 60 + minute } * 60 * 1_000_000)
}
4 -> {
let hour_str = string.slice(offset, 0, 2)
let minute_str = string.slice(offset, 2, 2)
use hour <- result.then(int.parse(hour_str))
use minute <- result.then(int.parse(minute_str))
Ok(sign * { hour * 60 + minute } * 60 * 1_000_000)
}
_ -> Error(Nil)
}
_ -> Error(Nil)
}
}
fn generate_offset(offset: Int) -> Result(String, Nil) {
use <- bool.guard(offset == 0, Ok("Z"))
case
[#(offset, duration.MicroSecond)]
|> duration.new
|> duration.decompose
{
[#(hour, duration.Hour), #(minute, duration.Minute)] ->
[
case hour > 0 {
True ->
string.concat([
"+",
hour
|> int.to_string
|> string.pad_left(2, "0"),
])
False ->
string.concat([
"-",
hour
|> int.absolute_value
|> int.to_string
|> string.pad_left(2, "0"),
])
},
minute
|> int.absolute_value
|> int.to_string
|> string.pad_left(2, "0"),
]
|> string.join(":")
|> Ok
[#(hour, duration.Hour)] ->
[
case hour > 0 {
True ->
string.concat([
"+",
hour
|> int.to_string
|> string.pad_left(2, "0"),
])
False ->
string.concat([
"-",
hour
|> int.absolute_value
|> int.to_string
|> string.pad_left(2, "0"),
])
},
"00",
]
|> string.join(":")
|> Ok
_ -> Error(Nil)
}
}
fn parse_date(date: String) -> Result(List(Int), Nil) {
let assert Ok(dash_pattern) =
regex.from_string(
"(\\d{4})(?:-(1[0-2]|0?[0-9]))?(?:-(3[0-1]|[1-2][0-9]|0?[0-9]))?",
)
case regex.scan(dash_pattern, date) {
[regex.Match(_, [option.Some(major)])] -> [int.parse(major), Ok(1), Ok(1)]
[regex.Match(_, [option.Some(major), option.Some(middle)])] -> [
int.parse(major),
int.parse(middle),
Ok(1),
]
[
regex.Match(
_,
[option.Some(major), option.Some(middle), option.Some(minor)],
),
] -> [int.parse(major), int.parse(middle), int.parse(minor)]
_ ->
parse_iso_section(
date,
"(\\d{4})(1[0-2]|0?[0-9])?(3[0-1]|[1-2][0-9]|0?[0-9])?",