/
datetime.lua
1318 lines (1162 loc) · 40 KB
/
datetime.lua
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
local ffi = require('ffi')
local buffer = require('buffer')
local tz = require('timezones')
--[[
`c-dt` library functions handles properly both positive and negative `dt`
values, where `dt` is a number of dates since Rata Die date (0001-01-01).
`c-dt` uses 32-bit integer number to store `dt` values, so range of
suported dates is limited to dates from -5879610-06-22 (INT32_MIN) to
+5879611-07-11 (INT32_MAX).
For better compactness of our typical data in MessagePack stream we shift
root of our time to the Unix Epoch date (1970-01-01), thus our 0 is
actually dt = 719163.
So here is a simple formula how convert our epoch-based seconds to dt values
dt = (secs / 86400) + 719163
Where 719163 is an offset of Unix Epoch (1970-01-01) since Rata Die
(0001-01-01) in dates.
]]
ffi.cdef[[
/* dt_core.h definitions */
typedef int dt_t;
typedef enum {
DT_MON = 1,
DT_MONDAY = 1,
DT_TUE = 2,
DT_TUESDAY = 2,
DT_WED = 3,
DT_WEDNESDAY = 3,
DT_THU = 4,
DT_THURSDAY = 4,
DT_FRI = 5,
DT_FRIDAY = 5,
DT_SAT = 6,
DT_SATURDAY = 6,
DT_SUN = 7,
DT_SUNDAY = 7,
} dt_dow_t;
dt_t tnt_dt_from_rdn (int n);
bool tnt_dt_from_ymd_checked(int y, int m, int d, dt_t *val);
void tnt_dt_to_ymd (dt_t dt, int *y, int *m, int *d);
dt_dow_t tnt_dt_dow (dt_t dt);
/* dt_util.h */
int tnt_dt_days_in_month (int y, int m);
/* dt_accessor.h */
int tnt_dt_year (dt_t dt);
int tnt_dt_month (dt_t dt);
int tnt_dt_doy (dt_t dt);
int tnt_dt_dom (dt_t dt);
dt_t tnt_dt_add_months (dt_t dt, int delta, dt_adjust_t adjust);
/* dt_parse_iso.h definitions */
size_t tnt_dt_parse_iso_date(const char *str, size_t len, dt_t *dt);
size_t tnt_dt_parse_iso_zone_lenient(const char *str, size_t len, int *offset);
/* Tarantool datetime functions - datetime.c */
size_t tnt_datetime_to_string(const struct datetime * date, char *buf,
ssize_t len);
size_t tnt_datetime_strftime(const struct datetime *date, char *buf,
uint32_t len, const char *fmt);
ssize_t tnt_datetime_parse_full(struct datetime *date, const char *str,
size_t len, const char *tzsuffix,
int32_t offset);
ssize_t tnt_datetime_parse_tz(const char *str, size_t len, time_t base,
int16_t *tzoffset, int16_t *tzindex);
size_t tnt_datetime_strptime(struct datetime *date, const char *buf,
const char *fmt);
void tnt_datetime_now(struct datetime *now);
bool tnt_datetime_totable(const struct datetime *date,
struct interval *out);
bool tnt_datetime_isdst(const struct datetime *date);
/* Tarantool interval support functions */
size_t tnt_interval_to_string(const struct interval *, char *, ssize_t);
int tnt_datetime_increment_by(struct datetime *self, int direction,
const struct interval *ival);
int tnt_datetime_datetime_sub(struct interval *res,
const struct datetime *lhs,
const struct datetime *rhs);
int tnt_interval_interval_sub(struct interval *lhs,
const struct interval *rhs);
int tnt_interval_interval_add(struct interval *lhs,
const struct interval *rhs);
/* Tarantool timezone support */
enum {
TZ_UTC = 0x01,
TZ_RFC = 0x02,
TZ_MILITARY = 0x04,
TZ_AMBIGUOUS = 0x08,
TZ_NYI = 0x10,
};
]]
local builtin = ffi.C
local math_modf = math.modf
local math_floor = math.floor
-- Unix, January 1, 1970, Thursday
local DAYS_EPOCH_OFFSET = 719163
local SECS_PER_DAY = 86400
local SECS_EPOCH_OFFSET = DAYS_EPOCH_OFFSET * SECS_PER_DAY
local TOSTRING_BUFSIZE = 64
local IVAL_TOSTRING_BUFSIZE = 96
local STRFTIME_BUFSIZE = 128
-- minimum supported date - -5879610-06-22
local MIN_DATE_YEAR = -5879610
local MIN_DATE_MONTH = 6
local MIN_DATE_DAY = 22
-- maximum supported date - 5879611-07-11
local MAX_DATE_YEAR = 5879611
local MAX_DATE_MONTH = 7
local MAX_DATE_DAY = 11
-- In the Julian calendar, the average year length is
-- 365 1/4 days = 365.25 days. This gives an error of
-- about 1 day in 128 years.
local AVERAGE_DAYS_YEAR = 365.25
local AVERAGE_WEEK_YEAR = AVERAGE_DAYS_YEAR / 7
local INT_MAX = 2147483647
-- -5879610-06-22
local MIN_DATE_TEXT = ('%d-%02d-%02d'):format(MIN_DATE_YEAR, MIN_DATE_MONTH,
MIN_DATE_DAY)
-- 5879611-07-11
local MAX_DATE_TEXT = ('%d-%02d-%02d'):format(MAX_DATE_YEAR, MAX_DATE_MONTH,
MAX_DATE_DAY)
local MAX_YEAR_RANGE = MAX_DATE_YEAR - MIN_DATE_YEAR
local MAX_MONTH_RANGE = MAX_YEAR_RANGE * 12
local MAX_WEEK_RANGE = MAX_YEAR_RANGE * AVERAGE_WEEK_YEAR
local MAX_DAY_RANGE = MAX_YEAR_RANGE * AVERAGE_DAYS_YEAR
local MAX_HOUR_RANGE = MAX_DAY_RANGE * 24
local MAX_MIN_RANGE = MAX_HOUR_RANGE * 60
local MAX_SEC_RANGE = MAX_DAY_RANGE * SECS_PER_DAY
local MAX_NSEC_RANGE = INT_MAX
local MAX_USEC_RANGE = math_floor(MAX_NSEC_RANGE / 1e3)
local MAX_MSEC_RANGE = math_floor(MAX_NSEC_RANGE / 1e6)
local DEF_DT_ADJUST = builtin.DT_LIMIT
local date_tostr_stash =
buffer.ffi_stash_new(string.format('char[%s]', TOSTRING_BUFSIZE))
local date_tostr_stash_take = date_tostr_stash.take
local date_tostr_stash_put = date_tostr_stash.put
local ival_tostr_stash =
buffer.ffi_stash_new(string.format('char[%s]', IVAL_TOSTRING_BUFSIZE))
local ival_tostr_stash_take = ival_tostr_stash.take
local ival_tostr_stash_put = ival_tostr_stash.put
local date_strf_stash =
buffer.ffi_stash_new(string.format('char[%s]', STRFTIME_BUFSIZE))
local date_strf_stash_take = date_strf_stash.take
local date_strf_stash_put = date_strf_stash.put
local date_dt_stash = buffer.ffi_stash_new('dt_t[1]')
local date_dt_stash_take = date_dt_stash.take
local date_dt_stash_put = date_dt_stash.put
local date_int16_stash = buffer.ffi_stash_new('int16_t[1]')
local date_int16_stash_take = date_int16_stash.take
local date_int16_stash_put = date_int16_stash.put
local datetime_t = ffi.typeof('struct datetime')
local interval_t = ffi.typeof('struct interval')
local function is_interval(o)
return ffi.istype(interval_t, o)
end
local function is_datetime(o)
return ffi.istype(datetime_t, o)
end
local function is_table(o)
return type(o) == 'table'
end
local function check_date(o, message)
if not is_datetime(o) then
return error(("%s: expected datetime, but received %s"):
format(message, type(o)), 2)
end
end
local function check_date_interval(o, message)
if not is_datetime(o) and not is_interval(o) then
return error(("%s: expected datetime or interval, but received %s"):
format(message, type(o)), 2)
end
end
local function check_interval(o, message)
if not is_interval(o) then
return error(("%s: expected interval, but received %s"):
format(message, type(o)), 2)
end
end
local function check_interval_table(o, message)
if not is_table(o) and not is_interval(o) then
return error(("%s: expected interval or table, but received %s"):
format(message, type(o)), 2)
end
end
local function check_date_interval_table(o, message)
if not is_table(o) and not is_datetime(o) and not is_interval(o) then
return error(("%s: expected datetime, interval or table, but received %s"):
format(message, type(o)), 2)
end
end
local function check_table(o, message)
if not is_table(o) then
return error(("%s: expected table, but received %s"):
format(message, type(o)), 2)
end
end
local function check_str(s, message)
if type(s) ~= 'string' then
return error(("%s: expected string, but received %s"):
format(message, type(s)), 2)
end
end
local function check_integer(v, message)
if v == nil then
return
end
if type(v) ~= 'number' or v % 1 ~= 0 then
error(('%s: integer value expected, but received %s'):
format(message, type(v)), 4)
end
end
local function check_str_or_nil(s, message)
if s ~= nil and type(s) ~= 'string' then
return error(("%s: expected string, but received %s"):
format(message, type(s)), 2)
end
end
-- range may be of a form of pair {from, to} or
-- tuple {fom, to, -1 in extra}
-- -1 is a special value (so far) used for days only
local function check_range(v, from, to, txt, extra)
if type(v) ~= 'number' then
error(('numeric value expected, but received %s'):
format(type(v)), 3)
end
if extra == v or (v >= from and v <= to) then
return
end
if extra == nil then
error(('value %d of %s is out of allowed range [%d, %d]'):
format(v, txt, from, to), 3)
else
error(('value %d of %s is out of allowed range [%d, %d..%d]'):
format(v, txt, extra, from, to), 3)
end
end
local function dt_from_ymd_checked(y, M, d)
local pdt = date_dt_stash_take()
local is_valid = builtin.tnt_dt_from_ymd_checked(y, M, d, pdt)
if not is_valid then
date_dt_stash_put(pdt)
error(('date %4d-%02d-%02d is invalid'):format(y, M, d))
end
local dt = pdt[0]
date_dt_stash_put(pdt)
return dt
end
-- check v value against maximum/minimum possible values
-- if there is nil then simply return default 0
local function checked_max_value(v, max, txt, def)
if v == nil then
return def
end
if type(v) ~= 'number' then
error(('numeric value expected, but received %s'):
format(type(v)), 2)
end
if v > -max and v < max then
return v
end
error(('value %s of %s is out of allowed range [%s, %s]'):
format(v, txt, -max, max), 4)
end
local function bool2int(b)
return b and 1 or 0
end
local adjust_xlat = {
none = builtin.DT_LIMIT,
last = builtin.DT_SNAP,
excess = builtin.DT_EXCESS,
}
local function interval_init(year, month, week, day, hour, min, sec, nsec,
adjust)
return ffi.new(interval_t, sec, min, hour, day, week, month, year, nsec,
adjust)
end
local function interval_new_copy(obj)
return interval_init(obj.year, obj.month, obj.week, obj.day, obj.hour,
obj.min, obj.sec, obj.nsec, obj.adjust)
end
local function interval_decode_args(obj)
if is_interval(obj) then
return obj
end
local year = checked_max_value(obj.year, MAX_YEAR_RANGE, 'year', 0)
check_integer(year, 'year')
local month = checked_max_value(obj.month, MAX_MONTH_RANGE, 'month', 0)
check_integer(month, 'month')
local adjust = adjust_xlat[obj.adjust] or DEF_DT_ADJUST
local weeks = checked_max_value(obj.week, MAX_WEEK_RANGE, 'week', 0)
local days = checked_max_value(obj.day, MAX_DAY_RANGE, 'day', 0)
check_integer(days, 'day')
local hours = checked_max_value(obj.hour, MAX_HOUR_RANGE, 'hour', 0)
check_integer(hours, 'hour')
local minutes = checked_max_value(obj.min, MAX_MIN_RANGE, 'min', 0)
check_integer(minutes, 'min')
local secs = checked_max_value(obj.sec, MAX_SEC_RANGE, 'sec', 0)
check_integer(secs, 'sec')
local nsec = checked_max_value(obj.nsec, MAX_NSEC_RANGE, 'nsec')
local usec = checked_max_value(obj.usec, MAX_USEC_RANGE, 'usec')
local msec = checked_max_value(obj.msec, MAX_MSEC_RANGE, 'msec')
local count_usec = bool2int(nsec ~= nil) + bool2int(usec ~= nil) +
bool2int(msec ~= nil)
if count_usec > 1 then
error('only one of nsec, usec or msecs may be defined '..
'simultaneously', 3)
end
nsec = (msec or 0) * 1e6 + (usec or 0) * 1e3 + (nsec or 0)
return interval_init(year, month, weeks, days, hours, minutes, secs, nsec,
adjust)
end
local function interval_new(obj)
if obj == nil then
return interval_init(0, 0, 0, 0, 0, 0, 0, 0, DEF_DT_ADJUST)
end
check_table(obj, 'interval.new()')
return interval_decode_args(obj)
end
-- convert from epoch related time to Rata Die related
local function local_rd(secs)
return math_floor((secs + SECS_EPOCH_OFFSET) / SECS_PER_DAY)
end
-- convert UTC seconds to local seconds, adjusting by timezone
local function local_secs(obj)
return obj.epoch + obj.tzoffset * 60
end
local function utc_secs(epoch, tzoffset)
return epoch - tzoffset * 60
end
local function time_delocalize(self)
self.epoch = local_secs(self)
self.tzoffset = 0
end
local function time_localize(self, offset)
self.epoch = utc_secs(self.epoch, offset)
self.tzoffset = offset
end
-- get epoch seconds, shift to the local timezone
-- adjust from 1970-related to 0000-related time
-- then return dt in those coordinates (number of days
-- since Rata Die date)
local function local_dt(obj)
return builtin.tnt_dt_from_rdn(local_rd(local_secs(obj)))
end
local function datetime_cmp(lhs, rhs, is_raising)
if not is_datetime(lhs) or not is_datetime(rhs) then
if is_raising then
error('incompatible types for datetime comparison', 3)
else
return nil
end
end
local sdiff = lhs.epoch - rhs.epoch
return sdiff ~= 0 and sdiff or (lhs.nsec - rhs.nsec)
end
local function datetime_eq(lhs, rhs)
return datetime_cmp(lhs, rhs, false) == 0
end
local function datetime_lt(lhs, rhs)
return datetime_cmp(lhs, rhs, true) < 0
end
local function datetime_le(lhs, rhs)
return datetime_cmp(lhs, rhs, true) <= 0
end
--[[
parse_tzoffset accepts time-zone strings in both basic
and extended iso-8601 formats.
Basic Extended
Z N/A
+hh N/A
-hh N/A
+hhmm +hh:mm
-hhmm -hh:mm
Returns timezone offset in minutes if string was accepted
by parser, otherwise raise an error.
]]
local function parse_tzoffset(str)
local offset = ffi.new('int[1]')
local len = builtin.tnt_dt_parse_iso_zone_lenient(str, #str, offset)
if len ~= #str then
error(('invalid time-zone format %s'):format(str), 3)
end
return offset[0]
end
local function epoch_from_dt(dt)
return (dt - DAYS_EPOCH_OFFSET) * SECS_PER_DAY
end
-- Use Olson facilities to determine whether local time in obj is DST
local function datetime_isdst(obj)
return builtin.tnt_datetime_isdst(obj)
end
--[[
Parse timezone name similar way as datetime_parse_full parse
full literal.
]]
local function parse_tzname(base_epoch, tzname)
check_str(tzname, 'parse_tzname()')
local ptzindex = date_int16_stash_take()
local ptzoffset = date_int16_stash_take()
local len = builtin.tnt_datetime_parse_tz(tzname, #tzname, base_epoch,
ptzoffset, ptzindex)
if len > 0 then
local tzoffset, tzindex = ptzoffset[0], ptzindex[0]
date_int16_stash_put(ptzoffset)
date_int16_stash_put(ptzindex)
return tzoffset, tzindex
end
date_int16_stash_put(ptzoffset)
date_int16_stash_put(ptzindex)
if len == -builtin.TZ_NYI then
error(("could not parse '%s' - nyi timezone"):format(tzname))
elseif len == -builtin.TZ_AMBIGUOUS then
error(("could not parse '%s' - ambiguous timezone"):format(tzname))
else -- len <= 0
error(("could not parse '%s'"):format(tzname))
end
end
local function datetime_new_raw(epoch, nsec, tzoffset, tzindex)
local dt_obj = ffi.new(datetime_t)
dt_obj.epoch = epoch
dt_obj.nsec = nsec
dt_obj.tzoffset = tzoffset
dt_obj.tzindex = tzindex
return dt_obj
end
local function datetime_new_copy(obj)
return datetime_new_raw(obj.epoch, obj.nsec, obj.tzoffset, obj.tzindex)
end
local function datetime_new_dt(dt, secs, nanosecs, offset, tzindex)
secs = secs or 0
nanosecs = nanosecs or 0
offset = offset or 0
tzindex = tzindex or 0
return datetime_new_raw(epoch_from_dt(dt) + secs - offset * 60, nanosecs,
offset, tzindex)
end
local function get_timezone(offset, msg)
if type(offset) == 'number' then
return offset
elseif type(offset) == 'string' then
return parse_tzoffset(offset)
else
error(('%s: string or number expected, but received %s'):
format(msg, offset), 3)
end
end
-- create datetime given attribute values from obj
local function datetime_new(obj)
if obj == nil then
return datetime_new_raw(0, 0, 0, 0)
end
check_table(obj, 'datetime.new()')
local ymd = false
local hms = false
local dt = DAYS_EPOCH_OFFSET
local y = obj.year
if y ~= nil then
check_range(y, MIN_DATE_YEAR, MAX_DATE_YEAR, 'year')
ymd = true
end
local M = obj.month
if M ~= nil then
check_range(M, 1, 12, 'month')
ymd = true
end
local d = obj.day
if d ~= nil then
check_range(d, 1, 31, 'day', -1)
ymd = true
end
local h = obj.hour
if h ~= nil then
check_range(h, 0, 23, 'hour')
hms = true
end
local m = obj.min
if m ~= nil then
check_range(m, 0, 59, 'min')
hms = true
end
local s = obj.sec
if s ~= nil then
check_range(s, 0, 60, 'sec')
hms = true
end
local nsec, usec, msec = obj.nsec, obj.usec, obj.msec
local count_usec = bool2int(nsec ~= nil) + bool2int(usec ~= nil) +
bool2int(msec ~= nil)
if count_usec > 0 then
if count_usec > 1 then
error('only one of nsec, usec or msecs may be defined '..
'simultaneously', 2)
end
if usec ~= nil then
check_range(usec, 0, 1e6, 'usec')
nsec = usec * 1e3
elseif msec ~= nil then
check_range(msec, 0, 1e3, 'msec')
nsec = msec * 1e6
else
check_range(nsec, 0, 1e9, 'nsec')
end
else
nsec = 0
end
local ts = obj.timestamp
if ts ~= nil then
if ymd then
error('timestamp is not allowed if year/month/day provided', 2)
end
if hms then
error('timestamp is not allowed if hour/min/sec provided', 2)
end
if type(ts) ~= 'number' then
error(("bad timestamp ('number' expected, got '%s')"):format(type(ts)))
end
local fraction
s, fraction = math_modf(ts)
-- In case of negative fraction part we should
-- make it positive at the expense of the integer part.
-- Code below expects that "nsec" value is always positive.
if fraction < 0 then
s = s - 1
fraction = fraction + 1
end
-- if there are separate nsec, usec, or msec provided then
-- timestamp should be integer
if count_usec == 0 then
nsec = fraction * 1e9
elseif fraction ~= 0 then
error('only integer values allowed in timestamp '..
'if nsec, usec, or msecs provided', 2)
end
hms = true
end
local offset = obj.tzoffset
if offset ~= nil then
offset = get_timezone(offset, 'tzoffset')
-- at the moment the range of known timezones is UTC-12:00..UTC+14:00
-- https://en.wikipedia.org/wiki/List_of_UTC_time_offsets
check_range(offset, -720, 840, 'tzoffset')
end
-- .year, .month, .day
if ymd then
y = y or 1970
M = M or 1
d = d or 1
if d < 0 then
d = builtin.tnt_dt_days_in_month(y, M)
elseif d > 28 then
local day_in_month = builtin.tnt_dt_days_in_month(y, M)
if d > day_in_month then
error(('invalid number of days %d in month %d for %d'):
format(d, M, y), 3)
end
end
dt = dt_from_ymd_checked(y, M, d)
end
local tzindex = 0
local tzname = obj.tz
if tzname ~= nil then
offset, tzindex = parse_tzname(epoch_from_dt(dt), tzname)
end
-- .hour, .minute, .second
local secs = 0
if hms then
secs = (h or 0) * 3600 + (m or 0) * 60 + (s or 0)
end
return datetime_new_dt(dt, secs, nsec, offset or 0, tzindex)
end
--[[
Convert to text datetime values
- datetime will use ISO-8601 format:
1970-01-01T00:00Z
2021-08-18T16:57:08.981725+03:00
]]
local function datetime_tostring(self)
local buff = date_tostr_stash_take()
local len = builtin.tnt_datetime_to_string(self, buff, TOSTRING_BUFSIZE)
assert(len < TOSTRING_BUFSIZE)
local s = ffi.string(buff)
date_tostr_stash_put(buff)
return s
end
--[[
Convert to text interval values of different types
- depending on a values stored there generic interval
values may be displayed in the following format:
+12 secs
-23 minutes, 0 seconds
+12 hours, 23 minutes, 1 seconds
-7 days, -23 hours, -23 minutes, -1 seconds
- years will be displayed as
+10 years
- months will be displayed as:
+2 months
]]
local function interval_tostring(self)
check_interval(self, 'datetime.interval.tostring')
local buff = ival_tostr_stash_take()
local len = builtin.tnt_interval_to_string(self, buff, IVAL_TOSTRING_BUFSIZE)
if len < IVAL_TOSTRING_BUFSIZE then
local s = ffi.string(buff)
ival_tostr_stash_put(buff)
return s
end
-- slow path - reallocate for a fuller size, and then restart interval_to_string
ival_tostr_stash_put(buff)
buff = ffi.new('char[?]', len + 1)
builtin.tnt_interval_to_string(self, buff, len + 1)
return ffi.string(buff)
end
-- subtract/addition operation for date object and interval
local function datetime_increment_by(self, direction, ival)
local rc = builtin.tnt_datetime_increment_by(self, direction, ival)
if rc == 0 then
return self
end
local operation = direction >= 0 and 'addition' or 'subtraction'
if rc < 0 then
error(('%s makes date less than minimum allowed %s'):
format(operation, MIN_DATE_TEXT), 3)
else -- rc > 0
error(('%s makes date greater than maximum allowed %s'):
format(operation, MAX_DATE_TEXT), 3)
end
end
local check_ranges = {
[1] = {'year', MAX_YEAR_RANGE},
[2] = {'month', MAX_MONTH_RANGE},
[3] = {'week', MAX_WEEK_RANGE},
[4] = {'day', MAX_DAY_RANGE},
[5] = {'hour', MAX_HOUR_RANGE},
[6] = {'min', MAX_MIN_RANGE},
[7] = {'sec', MAX_SEC_RANGE},
[8] = {'nsec', MAX_NSEC_RANGE},
}
local function check_rc(rc, operation, obj)
-- fast path
if rc == 0 then
return obj
end
-- slow, error reporting path
local index = rc < 0 and -rc or rc
assert(index >= 1 and index <= 8)
local txt, max = unpack(check_ranges[index])
local v = obj[txt]
error(('%s moves value %s of %s out of allowed range [%s, %s]'):
format(operation, v, txt, -max, max), 3)
end
-- subtract operation when left is date, and right is date
local function datetime_datetime_sub(lhs, rhs)
local obj = interval_new()
local rc = builtin.tnt_datetime_datetime_sub(obj, lhs, rhs)
return check_rc(rc, 'subtraction', obj)
end
-- subtract operation for both left and right operands are intervals
local function interval_interval_sub(lhs, rhs)
local lobj = interval_decode_args(interval_new_copy(lhs))
local robj = interval_decode_args(rhs)
local rc = builtin.tnt_interval_interval_sub(lobj, robj)
return check_rc(rc, 'subtraction', lobj)
end
-- addition operation for both left and right operands are intervals
local function interval_interval_add(lhs, rhs)
local lobj = interval_decode_args(interval_new_copy(lhs))
local robj = interval_decode_args(rhs)
local rc = builtin.tnt_interval_interval_add(lobj, robj)
return check_rc(rc, 'addition', lobj)
end
local function date_first(lhs, rhs)
if is_datetime(rhs) then
return rhs, lhs
else
return lhs, rhs
end
end
local function error_incompatible(name)
error(("datetime:%s() - incompatible type of arguments"):
format(name), 3)
end
--[[
Matrix of subtraction operands eligibility and their result type
| | datetime | interval | table |
+-----------------+----------+----------+----------+
| datetime | interval | datetime | datetime |
| interval | | interval | interval |
| table | | | |
]]
local function datetime_interval_sub(lhs, rhs)
check_date_interval(lhs, "operator -")
check_date_interval_table(rhs, "operator -")
local left_is_interval = is_table(lhs) or is_interval(lhs)
local right_is_interval = is_table(rhs) or is_interval(rhs)
-- left is date, right is interval
if not left_is_interval and right_is_interval then
return datetime_increment_by(datetime_new_copy(lhs), -1,
interval_decode_args(rhs))
-- left is date, right is date
elseif not left_is_interval and not right_is_interval then
return datetime_datetime_sub(lhs, rhs)
-- both left and right are intervals
elseif left_is_interval and right_is_interval then
return interval_interval_sub(lhs, rhs)
else
error_incompatible("operator -")
end
end
--[[
Matrix of addition operands eligibility and their result type
| | datetime | interval | table |
+-----------------+----------+----------+----------+
| datetime | | datetime | datetime |
| interval | datetime | interval | interval |
| table | | | |
]]
local function datetime_interval_add(lhs, rhs)
lhs, rhs = date_first(lhs, rhs)
check_date_interval(lhs, "operator +")
check_interval_table(rhs, "operator +")
local left_is_interval = is_table(lhs) or is_interval(lhs)
local right_is_interval = is_table(rhs) or is_interval(rhs)
-- left is date, right is interval
if not left_is_interval and right_is_interval then
local obj = datetime_new_copy(lhs)
return datetime_increment_by(obj, 1, interval_decode_args(rhs))
-- both left and right are intervals
elseif left_is_interval and right_is_interval then
return interval_interval_add(lhs, rhs)
else
error_incompatible("operator +")
end
end
--[[
Parse partial ISO-8601 date string
Accepted formats are:
Basic Extended
20121224 2012-12-24 Calendar date (ISO 8601)
2012359 2012-359 Ordinal date (ISO 8601)
2012W521 2012-W52-1 Week date (ISO 8601)
2012Q485 2012-Q4-85 Quarter date
Returns pair of constructed datetime object, and length of string
which has been accepted by parser.
]]
local function datetime_parse_date(str)
check_str(str, 'datetime.parse_date()')
local dt = date_dt_stash_take()
local len = tonumber(builtin.tnt_dt_parse_iso_date(str, #str, dt))
if len == 0 then
date_dt_stash_put(dt)
error(('invalid date format %s'):format(str), 2)
end
local d = datetime_new_dt(dt[0])
date_dt_stash_put(dt)
return d, tonumber(len)
end
--[[
datetime parse function for strings in extended iso-8601 format
assumes to deal with date T time time_zone at once
date [T] time [ ] time_zone
Returns constructed datetime object and length of accepted string.
]]
local function datetime_parse_full(str, tzname, offset)
check_str(str, 'datetime.parse()')
local date = ffi.new(datetime_t)
local len = builtin.tnt_datetime_parse_full(date, str, #str, tzname, offset)
if len > 0 then
return date, tonumber(len)
elseif len == -builtin.TZ_NYI then
error(("could not parse '%s' - nyi timezone"):format(str))
elseif len == -builtin.TZ_AMBIGUOUS then
error(("could not parse '%s' - ambiguous timezone"):format(str))
else -- len <= 0
error(("could not parse '%s'"):format(str))
end
end
--[[
Parse datetime string given `strptime` like format.
Returns constructed datetime object and length of accepted string.
]]
local function datetime_parse_format(str, fmt)
local date = ffi.new(datetime_t)
local len = builtin.tnt_datetime_strptime(date, str, fmt)
if len == 0 then
error(("could not parse '%s' using '%s' format"):format(str, fmt))
end
return date, tonumber(len)
end
local function datetime_parse_from(str, obj)
check_str(str, 'datetime.parse()')
local fmt = ''
local tzoffset
local tzname
if obj ~= nil then
check_table(obj, 'datetime.parse()')
fmt = obj.format
tzoffset = obj.tzoffset
tzname = obj.tz
end
check_str_or_nil(fmt, 'datetime.parse()')
local offset = 0
if tzoffset ~= nil then
offset = get_timezone(tzoffset, 'tzoffset')
check_range(offset, -720, 840, 'tzoffset')
end
if tzname ~= nil then
check_str(tzname, 'datetime.parse()')
end
if not fmt or fmt == '' or fmt == 'iso8601' or fmt == 'rfc3339' then
-- Effect of .tz overrides .tzoffset
return datetime_parse_full(str, tzname, offset)
else
return datetime_parse_format(str, fmt)
end
end
--[[
Create datetime object representing current time using microseconds
platform timer and local timezone information.
]]
local function datetime_now()
local d = datetime_new_raw(0, 0, 0, 0)
builtin.tnt_datetime_now(d)
return d
end
-- addition or subtraction from date/time of a given interval
-- described via table direction should be +1 or -1
local function datetime_shift(self, o, direction)
assert(direction == -1 or direction == 1)
local title = direction > 0 and "datetime.add" or "datetime.sub"
check_interval_table(o, title)
return datetime_increment_by(self, direction, interval_decode_args(o))
end
--[[
dt_dow() returns days of week in range: 1=Monday .. 7=Sunday
convert it to os.date() wday which is in range: 1=Sunday .. 7=Saturday
]]
local function dow_to_wday(dow)
return tonumber(dow) % 7 + 1
end
--[[
Return table in os.date('*t') format, but with timezone
and nanoseconds
]]
local function datetime_totable(self)
check_date(self, 'datetime.totable()')
local dt = local_dt(self)
local tmp_ival = interval_new()
local rc = builtin.tnt_datetime_totable(self, tmp_ival)
assert(rc == true)
return {
year = tmp_ival.year,
month = tmp_ival.month,
yday = builtin.tnt_dt_doy(dt),
wday = dow_to_wday(builtin.tnt_dt_dow(dt)),
day = tmp_ival.day,
hour = tmp_ival.hour,
min = tmp_ival.min,
sec = tmp_ival.sec,
isdst = datetime_isdst(self),
nsec = self.nsec,
tzoffset = self.tzoffset,
}
end
local function datetime_update_dt(self, dt)
local epoch = self.epoch
local secs_day = epoch % SECS_PER_DAY
self.epoch = (dt - DAYS_EPOCH_OFFSET) * SECS_PER_DAY + secs_day
end
local function datetime_ymd_update(self, y, M, d)
if d < 0 then
d = builtin.tnt_dt_days_in_month(y, M)
elseif d > 28 then
local day_in_month = builtin.tnt_dt_days_in_month(y, M)
if d > day_in_month then
error(('invalid number of days %d in month %d for %d'):
format(d, M, y), 3)
end
end
local dt = dt_from_ymd_checked(y, M, d)
datetime_update_dt(self, dt)
end
local function datetime_hms_update(self, h, m, s)
local epoch = self.epoch