-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1202 lines (1120 loc) · 39.1 KB
/
index.js
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
const nopeRedis = require('./nope-redis');
nopeRedis.config({ isMemoryStatsEnabled: false, defaultTtl: 1300 });
const global_config = {
locales: 'en-en',
options: {
weekday: 'long',
},
};
const format_types = {
dddd: 'dddd',
YYYY: 'YYYY',
DD: 'DD',
MM: 'MM',
'YYYY-MM-DD': 'YYYY-MM-DD',
'YYYY-MM-DD HH:mm:ss': 'YYYY-MM-DD HH:mm:ss',
'YYYY-MM-DD HH:mm': 'YYYY-MM-DD HH:mm',
'YYYY.MM.DD': 'YYYY.MM.DD',
YYYYMMDD: 'YYYYMMDD',
'YYYY.MM.DD HH:mm:ss': 'YYYY.MM.DD HH:mm:ss',
'YYYY.MM.DD HH:mm': 'YYYY.MM.DD HH:mm',
'DD.MM.YYYY': 'DD.MM.YYYY',
'DD.MM.YYYY HH:mm:ss': 'DD.MM.YYYY HH:mm:ss',
'DD.MM.YYYY HH:mm': 'DD.MM.YYYY HH:mm',
'DD-MM-YYYY': 'DD-MM-YYYY',
'DD-MM-YYYY HH:mm:ss': 'DD-MM-YYYY HH:mm:ss',
'DD-MM-YYYY HH:mm': 'DD-MM-YYYY HH:mm',
'DD MMMM YYYY': 'DD MMMM YYYY',
'DD MMMM YYYY dddd': 'DD MMMM YYYY dddd',
'DD MMMM dddd YYYY': 'DD MMMM dddd YYYY',
'MMMM YYYY': 'MMMM YYYY',
'HH:mm:ss': 'HH:mm:ss',
'HH:mm': 'HH:mm',
HH: 'HH',
mm: 'mm',
ss: 'ss',
MMM: 'MMM', // Short month name (Jan, Feb, etc.)
MMMM: 'MMMM', // Full month name (January, February, etc.)
ddd: 'ddd', // Short weekday name (Mon, Tue, etc.)
'DD MMM YYYY': 'DD MMM YYYY', // 01 Jan 2024
'DD MMM': 'DD MMM', // 01 Jan
'MMM YYYY': 'MMM YYYY', // Jan 2024
'DD MMM YYYY HH:mm': 'DD MMM YYYY HH:mm', // 01 Jan 2024 13:45
};
const format_types_regex = {
YYYY: /^(17|18|19|20|21)\d\d$/,
MM: /^(0[1-9]|1[0-2])$/,
DD: /^(0[1-9]|[12][0-9]|3[01])$/,
'YYYY-MM-DD': /^(|17|18|19|20|21)\d\d-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/,
YYYYMMDD: /^(|17|18|19|20|21)\d\d(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$/,
'YYYY-MM-DD HH:mm:ss': /^(|17|18|19|20|21)\d\d-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) ([01]\d|2[0-9]):([0-5]\d):([0-5]\d)$/,
'YYYY-MM-DD HH:mm': /^(|17|18|19|20|21)\d\d-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) ([01]\d|2[0-9]):([0-5]\d)$/,
'YYYY.MM.DD': /^(|17|18|19|20|21)\d\d\.(0[1-9]|1[0-2])\.(0[1-9]|[12][0-9]|3[01])$/,
'YYYY.MM.DD HH:mm:ss': /^(|17|18|19|20|21)\d\d\.(0[1-9]|1[0-2])\.(0[1-9]|[12][0-9]|3[01]) ([01]\d|2[0-9]):([0-5]\d):([0-5]\d)$/,
'YYYY.MM.DD HH:mm': /^(|17|18|19|20|21)\d\d\.(0[1-9]|1[0-2])\.(0[1-9]|[12][0-9]|3[01]) ([01]\d|2[0-9]):([0-5]\d)$/,
'DD.MM.YYYY': /^(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[0-2])\.(|17|18|19|20|21)\d\d$/,
'DD.MM.YYYY HH:mm:ss': /^(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[0-2])\.(|17|18|19|20|21)\d\d ([01]\d|2[0-9]):([0-5]\d):([0-5]\d)$/,
'DD.MM.YYYY HH:mm': /^(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[0-2])\.(|17|18|19|20|21)\d\d ([01]\d|2[0-9]):([0-5]\d)$/,
'DD-MM-YYYY': /^(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[0-2])-(|17|18|19|20|21)\d\d$/,
'DD-MM-YYYY HH:mm:ss': /^(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[0-2])-(|17|18|19|20|21)\d\d ([01]\d|2[0-9]):([0-5]\d):([0-5]\d)$/,
'DD-MM-YYYY HH:mm': /^(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[0-2])-(|17|18|19|20|21)\d\d ([01]\d|2[0-9]):([0-5]\d)$/,
'DD MMMM YYYY':
/^(0[1-9]|[12][0-9]|3[01]) (January|February|March|April|May|June|July|August|September|October|November|December) (|17|18|19|20|21)\d\d$/,
'DD MMMM YYYY dddd':
/^(0[1-9]|[12][0-9]|3[01]) (January|February|March|April|May|June|July|August|September|October|November|December) (|17|18|19|20|21)\d\d (Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)$/,
'MMMM YYYY': /^(January|February|March|April|May|June|July|August|September|October|November|December) (|17|18|19|20|21)\d\d$/,
'DD MMMM dddd YYYY':
/^(0[1-9]|[12][0-9]|3[01]) (January|February|March|April|May|June|July|August|September|October|November|December) (Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday) (|17|18|19|20|21)\d\d$/,
'HH:mm:ss': /^([01]\d|2[0-9]):([0-5]\d):([0-5]\d)$/,
'HH:mm': /^([01]\d|2[0-9]):([0-5]\d)$/,
HH: /^([01]\d|2[0-9])$/,
mm: /^([0-5]\d)$/,
ss: /^([0-5]\d)$/,
MMM: /^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)$/,
MMMM: /^(January|February|March|April|May|June|July|August|September|October|November|December)$/,
ddd: /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)$/,
'DD MMM YYYY': /^(0[1-9]|[12][0-9]|3[01]) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (|17|18|19|20|21)\d\d$/,
'DD MMM': /^(0[1-9]|[12][0-9]|3[01]) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)$/,
'MMM YYYY': /^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (|17|18|19|20|21)\d\d$/,
'DD MMM YYYY HH:mm': /^(0[1-9]|[12][0-9]|3[01]) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (|17|18|19|20|21)\d\d ([01]\d|2[0-9]):([0-5]\d)$/,
};
const timeInMilliseconds = {
year: 365 * 24 * 60 * 60 * 1000, // 1 year (365 days)
month: 31 * 24 * 60 * 60 * 1000, // 1 month (31 days)
week: 7 * 24 * 60 * 60 * 1000, // 1 week (7 days)
day: 24 * 60 * 60 * 1000, // 1 day (24 hours)
hour: 60 * 60 * 1000, // 1 hour
minute: 60 * 1000, // 1 minute
second: 1000, // 1 second
};
const howManySeconds = {
year: 31556926,
month: 2629743,
week: 604800,
day: 86400,
hour: 3600,
minute: 60,
};
/**
* @kkDate method
*/
class KkDate {
/**
*
* @param {string|Date|KkDate} date - date/datetime/time
*/
constructor(...params) {
let is_can_cache = false;
let cached = false;
if (params.length === 0) {
this.date = new Date();
} else {
const date = params[0];
if (Number.isInteger(date)) {
const stringed_date_length = `${date}`.length;
if (stringed_date_length <= 10) {
this.date = new Date(date * 1000);
} else if (stringed_date_length > 10) {
this.date = new Date(date);
}
} else if (isKkDate(date)) {
this.date = new Date(date.date.toUTCString());
} else if (date instanceof Date) {
this.date = new Date(date.toUTCString());
} else {
is_can_cache = true;
cached = nopeRedis.getItem(`${date}`);
if (!cached) {
if (isValid(date, format_types['HH:mm:ss']) || isValid(date, format_types['HH:mm'])) {
let [hours, minutes, seconds] = date.split(':').map(Number);
if (hours >= 24) {
const extraDays = Math.floor(hours / 24);
hours = hours % 24;
const dateObj = new Date();
dateObj.setDate(dateObj.getDate() + extraDays);
const newDay = String(dateObj.getDate()).padStart(2, '0');
const newMonth = String(dateObj.getMonth() + 1).padStart(2, '0');
const newYear = dateObj.getFullYear();
let date_string = `${newYear}-${newMonth}-${newDay}T${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
if (seconds) {
date_string += seconds.toString().padStart(2, '0');
}
this.date = new Date(date_string);
} else {
this.date = new Date(`${new Date().toISOString().split('T')[0]} ${date}`);
}
} else {
this.date = false;
if (isValid(date, format_types['DD.MM.YYYY HH:mm:ss'])) {
const [datePart, timePart] = date.split(' ');
const [day, month, year] = datePart.split('.');
let [hours, minutes, seconds] = timePart.split(':').map(Number);
if (hours >= 24) {
const extraDays = Math.floor(hours / 24);
hours = hours % 24;
const dateObj = new Date(`${year}-${month}-${day}`);
dateObj.setDate(dateObj.getDate() + extraDays);
const newDay = String(dateObj.getDate()).padStart(2, '0');
const newMonth = String(dateObj.getMonth() + 1).padStart(2, '0');
const newYear = dateObj.getFullYear();
this.date = new Date(
`${newYear}-${newMonth}-${newDay}T${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`,
);
} else {
this.date = new Date(`${year}-${month}-${day}T${timePart}`);
}
} else if (isValid(date, format_types['DD.MM.YYYY HH:mm'])) {
const [datePart, timePart] = date.split(' ');
const [day, month, year] = datePart.split('.');
let [hours, minutes] = timePart.split(':').map(Number);
if (hours >= 24) {
const extraDays = Math.floor(hours / 24);
hours = hours % 24;
const dateObj = new Date(`${year}-${month}-${day}`);
dateObj.setDate(dateObj.getDate() + extraDays);
const newDay = String(dateObj.getDate()).padStart(2, '0');
const newMonth = String(dateObj.getMonth() + 1).padStart(2, '0');
const newYear = dateObj.getFullYear();
this.date = new Date(`${newYear}-${newMonth}-${newDay}T${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`);
} else {
this.date = new Date(`${year}-${month}-${day}T${timePart}`);
}
} else if (isValid(date, format_types['DD.MM.YYYY'])) {
const [day, month, year] = date.split('.');
this.date = new Date(`${year}-${month}-${day}`);
} else if (isValid(date, format_types['YYYY-MM-DD HH:mm:ss'])) {
const [datePart, timePart] = date.split(' ');
const [year, month, day] = datePart.split('-');
let [hours, minutes, seconds] = timePart.split(':').map(Number);
if (hours >= 24) {
const extraDays = Math.floor(hours / 24);
hours = hours % 24;
const dateObj = new Date(`${year}-${month}-${day}`);
dateObj.setDate(dateObj.getDate() + extraDays);
const newDay = String(dateObj.getDate()).padStart(2, '0');
const newMonth = String(dateObj.getMonth() + 1).padStart(2, '0');
const newYear = dateObj.getFullYear();
this.date = new Date(
`${newYear}-${newMonth}-${newDay}T${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`,
);
} else {
this.date = new Date(`${year}-${month}-${day}T${timePart}`);
}
} else if (isValid(date, format_types['YYYY-MM-DD HH:mm'])) {
const [datePart, timePart] = date.split(' ');
const [year, month, day] = datePart.split('-');
let [hours, minutes] = timePart.split(':').map(Number);
if (hours >= 24) {
const extraDays = Math.floor(hours / 24);
hours = hours % 24;
const dateObj = new Date(`${year}-${month}-${day}`);
dateObj.setDate(dateObj.getDate() + extraDays);
const newDay = String(dateObj.getDate()).padStart(2, '0');
const newMonth = String(dateObj.getMonth() + 1).padStart(2, '0');
const newYear = dateObj.getFullYear();
this.date = new Date(`${newYear}-${newMonth}-${newDay}T${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`);
} else {
this.date = new Date(`${year}-${month}-${day}T${timePart}`);
}
} else if (isValid(date, format_types['YYYY.MM.DD HH:mm:ss'])) {
const [datePart, timePart] = date.split(' ');
const [year, month, day] = datePart.split('.');
let [hours, minutes, seconds] = timePart.split(':').map(Number);
if (hours >= 24) {
const extraDays = Math.floor(hours / 24);
hours = hours % 24;
const dateObj = new Date(`${year}-${month}-${day}`);
dateObj.setDate(dateObj.getDate() + extraDays);
const newDay = String(dateObj.getDate()).padStart(2, '0');
const newMonth = String(dateObj.getMonth() + 1).padStart(2, '0');
const newYear = dateObj.getFullYear();
this.date = new Date(
`${newYear}-${newMonth}-${newDay}T${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`,
);
} else {
this.date = new Date(`${year}-${month}-${day}T${timePart}`);
}
} else if (isValid(date, format_types['YYYY.MM.DD HH:mm'])) {
const [datePart, timePart] = date.split(' ');
const [year, month, day] = datePart.split('.');
let [hours, minutes] = timePart.split(':').map(Number);
if (hours >= 24) {
const extraDays = Math.floor(hours / 24);
hours = hours % 24;
const dateObj = new Date(`${year}-${month}-${day}`);
dateObj.setDate(dateObj.getDate() + extraDays);
const newDay = String(dateObj.getDate()).padStart(2, '0');
const newMonth = String(dateObj.getMonth() + 1).padStart(2, '0');
const newYear = dateObj.getFullYear();
this.date = new Date(`${newYear}-${newMonth}-${newDay}T${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}}`);
} else {
this.date = new Date(`${year}-${month}-${day}T${timePart}`);
}
} else if (isValid(date, format_types['DD-MM-YYYY'])) {
const [day, month, year] = date.split('-');
this.date = new Date(`${year}-${month}-${day}`);
} else if (isValid(date, format_types['DD-MM-YYYY HH:mm:ss'])) {
const [datePart, timePart] = date.split(' ');
const [day, month, year] = datePart.split('-');
let [hours, minutes, seconds] = timePart.split(':').map(Number);
if (hours >= 24) {
const extraDays = Math.floor(hours / 24);
hours = hours % 24;
const dateObj = new Date(`${year}-${month}-${day}`);
dateObj.setDate(dateObj.getDate() + extraDays);
const newDay = String(dateObj.getDate()).padStart(2, '0');
const newMonth = String(dateObj.getMonth() + 1).padStart(2, '0');
const newYear = dateObj.getFullYear();
this.date = new Date(
`${newYear}-${newMonth}-${newDay}T${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`,
);
} else {
this.date = new Date(`${year}-${month}-${day}T${timePart}`);
}
} else if (isValid(date, format_types['DD-MM-YYYY HH:mm'])) {
const [datePart, timePart] = date.split(' ');
const [day, month, year] = datePart.split('-');
let [hours, minutes] = timePart.split(':').map(Number);
if (hours >= 24) {
const extraDays = Math.floor(hours / 24);
hours = hours % 24;
const dateObj = new Date(`${year}-${month}-${day}`);
dateObj.setDate(dateObj.getDate() + extraDays);
const newDay = String(dateObj.getDate()).padStart(2, '0');
const newMonth = String(dateObj.getMonth() + 1).padStart(2, '0');
const newYear = dateObj.getFullYear();
this.date = new Date(`${newYear}-${newMonth}-${newDay}T${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`);
} else {
this.date = new Date(`${year}-${month}-${day}T${timePart}`);
}
} else if (isValid(date, format_types['YYYYMMDD'])) {
const year = String(date.substring(0, 4), 10); // Extract year
const month = String(date.substring(4, 6), 10); // Extract month
const day = String(date.substring(6, 8), 10); // Extract day
this.date = new Date(`${year}-${month}-${day}`);
}
if (this.date === false) {
this.date = new Date(`${date}`);
}
}
}
}
if (is_can_cache && cached) {
this.date = new Date(cached.getTime());
} else {
isInvalid(this.date);
if (is_can_cache) {
nopeRedis.setItem(`${date}`, new Date(this.date.getTime()));
}
}
}
}
/**
* returns native Date getTime value
*
* @returns {number|Error}
*/
getTime() {
isInvalid(this.date);
return this.date.getTime();
}
/**
* isBefore
*
* @param {string|Date|KkDate} date - date/datetime/time
* @returns {boolean|Error}
*/
isBefore(date) {
const converted = isKkDate(date) ? date.getTime() : new KkDate(date).getTime();
return this.getTime() < converted;
}
/**
* isSameOrBefore
*
* @param {string|Date|KkDate} date - date/datetime/time
* @returns {boolean|Error}
*/
isSameOrBefore(date) {
const converted = isKkDate(date) ? date.getTime() : new KkDate(date).getTime();
return this.getTime() <= converted;
}
/**
* isAfter
*
* @param {string|Date|KkDate} date - date/datetime/time
* @returns {boolean|Error}
*/
isAfter(date) {
const converted = isKkDate(date) ? date.getTime() : new KkDate(date).getTime();
return this.date.getTime() > converted;
}
/**
* isSameOrAfter
*
* @param {string|Date|KkDate} date - date/datetime/time
* @returns {boolean|Error}
*/
isSameOrAfter(date) {
const converted = isKkDate(date) ? date.getTime() : new KkDate(date).getTime();
return this.date.getTime() >= converted;
}
/**
* isSame
*
* @param {string|Date|KkDate} date - date/datetime/time
* @returns {boolean|Error}
*/
isSame(date) {
const converted = isKkDate(date) ? date.getTime() : new KkDate(date).getTime();
return this.date.getTime() === converted;
}
/**
* isBetween
*
* @param {string|Date|KkDate} date - date/datetime/time
* @param {string|Date|KkDate} date - date/datetime/time
* @returns {boolean|Error}
*/
isBetween(start, end) {
const starts = isKkDate(start) ? start.getTime() : new KkDate(start).getTime();
const ends = isKkDate(end) ? end.getTime() : new KkDate(end).getTime();
const date_time = this.date.getTime();
return date_time >= starts && date_time <= ends;
}
/**
* returns string of date
*
* @returns {string|Error}
*/
toString() {
isInvalid(this.date);
return this.date.toString();
}
/**
* The toDateString() method of Date instances returns a string representing the date portion of this date interpreted in the local timezone.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString
* @returns {string|Error}
*/
toDateString() {
isInvalid(this.date);
return this.date.toDateString();
}
/**
* The toISOString() method of Date instances returns a string representing this date in the date time string format, a simplified format based on ISO 8601, which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always UTC, as denoted by the suffix Z.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
*
* @returns {string|Error}
*/
toISOString() {
isInvalid(this.date);
return this.date.toISOString();
}
/**
* The toJSON() method of Date instances returns a string representing this date in the same ISO format as toISOString().
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON
*
* @returns {Object|Error}
*/
toJSON() {
isInvalid(this.date);
return this.date.toJSON();
}
/**
* The toUTCString() method of Date instances returns a string representing this date in the RFC 7231 format, with negative years allowed. The timezone is always UTC. toGMTString() is an alias of this method.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString
*
* @returns {string|Error}
*/
toUTCString() {
isInvalid(this.date);
return this.date.toUTCString();
}
/**
* The locales and options parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
*
* @param {object} options
* @returns {string|Error}
*/
toLocaleDateString(options) {
isInvalid(this.date);
if (!this.temp_config) {
this.temp_config = {
locales: global_config.locales || 'en-en',
};
}
return this.date.toLocaleDateString(this.temp_config.locales, options);
}
/**
* The toLocaleString() method of Date instances returns a string with a language-sensitive representation of this date in the local timezone. In implementations with Intl.DateTimeFormat API support, this method simply calls Intl.DateTimeFormat.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
*
* @param {object} options
* @returns {string|Error}
*/
toLocaleString(options) {
isInvalid(this.date);
if (!this.temp_config) {
this.temp_config = {
locales: global_config.locales || 'en-en',
};
}
return this.date.toLocaleString(this.temp_config.locales, options);
}
/**
* The toLocaleTimeString() method of Date instances returns a string with a language-sensitive representation of the time portion of this date in the local timezone. In implementations with Intl.DateTimeFormat API support, this method simply calls Intl.DateTimeFormat.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString
*
* @param {object} options
* @returns {string|Error}
*/
toLocaleTimeString(options) {
isInvalid(this.date);
if (!this.temp_config) {
this.temp_config = {
locales: global_config.locales || 'en-en',
};
}
return this.date.toLocaleTimeString(this.temp_config.locales, options);
}
/**
* The toTimeString() method of Date instances returns a string representing the time portion of this date interpreted in the local timezone.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString
*
* @returns {string|Error}
*/
toTimeString() {
isInvalid(this.date);
return this.date.toTimeString();
}
/**
* The valueOf() method of Date instances returns the number of milliseconds for this date since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf
*
* @returns {number|Error}
*/
valueOf() {
isInvalid(this.date);
return this.date.valueOf();
}
/**
* This is a pretty robust function for adding and subtracting time to an existing moment. To add time, specify the key of the time unit you want to add and the amount you want to add. Similarly, to subtract time, use the same key to subtract the amount of time.
*
* @param {number} amount
* @param {'seconds'|'minutes'|'hours'|'days'|'months'|'years'} type - The unit of time type
* @returns {KkDate|Error}
*/
add(amount, type) {
isInvalid(this.date);
if (typeof amount === 'number' && amount === 0) {
return this;
}
if (typeof amount !== 'number' || (typeof amount !== 'number' && typeof amount === 'object' && amount.$kk_date === undefined)) {
throw new Error('amount is wrong');
}
let defined_amount = amount;
let defined_type = type;
if (typeof amount === 'object' && amount.$kk_date) {
defined_type = 'seconds';
defined_amount = amount.$kk_date.milliseconds / timeInMilliseconds.second;
}
switch (defined_type) {
case 'days':
this.date.setDate(this.date.getDate() + defined_amount);
break;
case 'minutes':
this.date.setMinutes(this.date.getMinutes() + defined_amount);
break;
case 'seconds':
this.date.setSeconds(this.date.getSeconds() + defined_amount);
break;
case 'hours':
this.date.setHours(this.date.getHours() + defined_amount);
break;
case 'months': {
const currentDate = this.date.getDate();
const currentMonth = this.date.getMonth();
// Ay eklemenin düzgün olması için tarihin 1. gününü kullanıyoruz.
this.date.setDate(1);
this.date.setMonth(currentMonth + defined_amount);
// 29 çeken şubat aylarında, değişkendeki günle güncel günü karşılaştırıp son günü alıyoruz.
const lastDay = new Date(this.date.getFullYear(), this.date.getMonth() + 1, 0).getDate();
this.date.setDate(Math.min(currentDate, lastDay));
break;
}
case 'years': {
const year_amount = defined_amount * 12;
this.date.setMonth(this.date.getMonth() + year_amount);
break;
}
default:
throw new Error('type is wrong');
}
return this;
}
/**
*
* @param {string|Date|KkDate} start
* @param {string|Date|KkDate} end
* @param {'seconds'|'minutes'|'hours'|'days'|'months'|'years'} type - The unit of time type
* @param {boolean} is_decimal
* @returns {number|Error}
*/
diff(end, type, is_decimal = false) {
return diff(this, end, type, is_decimal, true);
}
/**
*
* @param {string|Date|KkDate} start
* @param {string|Date|KkDate} end
* @param {'seconds'|'minutes'|'hours'|'days'|'months'|'years'} type - The unit of time type
* @param {*} template
* @returns {Array|Error}
*/
diff_range(end, type, template = 'YYYY-MM-DD') {
const diffed = diff(this, end, type);
const rangeDates = [];
rangeDates.push(format(this, template));
for (let index = 1; index < diffed.diffTime + 1; index++) {
const date = new Date(this.date.getTime());
date.setSeconds(this.date.getSeconds() + diffed.type_value * index);
rangeDates.push(format(new KkDate(date), template));
}
return rangeDates;
}
/**
* set method of Date instances changes
*
* @param {'second'|'minute'|'hour'|'day'|'month'|'year'} type - The unit of time type
* @param {number} value
* @returns {KkDate|Error}
*/
set(type, value) {
switch (type) {
case 'second':
this.date.setSeconds(value);
break;
case 'minute':
this.date.setMinutes(value);
break;
case 'hour':
this.date.setHours(value);
break;
case 'day':
this.date.setDate(value);
break;
case 'month':
this.date.setMonth(value);
break;
case 'year':
this.date.setFullYear(value);
break;
default:
throw new Error('type wrong');
}
return this;
}
/**
* date format advanced
*
* @param {string} template
* @returns {string|Error}
*/
format_c(separator = ' ', ...template) {
isInvalid(this.date);
const result = [];
for (let index = 0; index < template.length; index++) {
result.push(formatter(this, template[index]));
}
return result.join(separator);
}
/**
* basic formatter
*
* @param {'YYYY-MM-DD HH:mm:ss'|'YYYY-MM-DDTHH:mm:ss'|'YYYY-MM-DD HH:mm'|'YYYY-MM-DD HH'|
* 'YYYY-MM-DD'|'YYYYMMDD'|'DD.MM.YYYY'|'YYYY.MM.DD HH:mm'|'YYYY.MM.DD HH'|
* 'YYYY.MM.DD HH:mm:ss'|'DD.MM.YYYY HH:mm:ss'|'DD.MM.YYYY HH:mm'|'dddd'|
* 'HH:mm:ss'|'HH:mm'|'X'|'x'|'DD-MM-YYYY'|'YYYY.MM.DD'|'DD-MM-YYYY HH'|
* 'DD-MM-YYYY HH:mm'|'DD-MM-YYYY HH:mm:ss'|'DD MMMM YYYY'|'DD MMMM YYYY dddd'|
* 'MMMM YYYY'|'DD MMMM dddd YYYY'|'MMM'|'MMMM'|'ddd'|'DD MMM YYYY'|'DD MMM'|
* 'MMM YYYY'|'DD MMM YYYY HH:mm'} template - format template
* @returns {string|Error}
*/
format(template) {
isInvalid(this.date);
return format(this, template);
}
/**
* @description kk-date config for in call
*
* @param {string} locales BCP 47 language tag
* @param {object} options
* @param {'short'|'long'} options.weekday
* @returns {Error|KkDate}
*/
config(locales, options = null) {
try {
new Intl.Locale(locales);
this.temp_config = {
locales: locales,
options: {
weekday: 'long',
},
};
if (options && typeof options === 'object') {
if (options.weekday) {
this.temp_config.options.weekday = options.weekday;
}
}
return this;
} catch (error) {
throw new Error('locales not valid for BCP 47, config error !');
}
}
/**
* returns boolean about invalid date or not
* if invalid will be turn false
*
* @returns {boolean}
*/
isValid() {
try {
isInvalid(this.date);
} catch (error) {
return false;
}
return true;
}
/**
* returns native Date Object
*
* @returns {Date|Error}
*/
getDate() {
isInvalid(this.date);
return this.date;
}
/**
* @description It divides the date string into parts and returns an object.
* @param {string} time - time seconds
* @returns {{year: number, month: number, week:number, day: number, hour: number, minute: number, second: number}}
*/
duration(time) {
const response = {
year: 0,
month: 0,
week: 0,
day: 0,
hour: 0,
minute: 0,
second: 0,
};
if (!time || typeof time !== 'number' || time < 0) {
throw new Error('Invalid time');
}
let seconds = time;
response.year = Math.floor(seconds / howManySeconds.year);
seconds = seconds % howManySeconds.year;
response.month = Math.floor(seconds / howManySeconds.month);
seconds = seconds % howManySeconds.month;
response.week = Math.floor(seconds / howManySeconds.week);
seconds = seconds % howManySeconds.week;
response.day = Math.floor(seconds / howManySeconds.day);
seconds = seconds % howManySeconds.day;
response.hour = Math.floor(seconds / howManySeconds.hour);
seconds = seconds % howManySeconds.hour;
response.minute = Math.floor(seconds / howManySeconds.minute);
seconds = seconds % howManySeconds.minute;
response.second = seconds;
return response;
}
}
/**
*
* @param {KkDate.date|Date} date
* @returns
*/
function isInvalid(date) {
try {
if (!date) {
throw new Error('Invalid Date');
}
if (Number.isNaN(date.valueOf())) {
throw new Error('Invalid Date');
}
} catch (error) {
throw new Error('Invalid Date');
}
return true;
}
/**
* isKkDate
*
* @param {KkDate} value
* @returns {boolean}
*/
function isKkDate(value = {}) {
if (value instanceof KkDate) {
return true;
}
return false;
}
/**
*
* @param {KkDate|Date} date
* @param {string} template
* @returns {string|Error}
*/
function format(date, template) {
switch (template) {
case 'YYYY-MM-DD HH:mm:ss':
return `${formatter(date, 'YYYY-MM-DD')} ${formatter(date, 'HH:mm:ss')}`;
case 'YYYY-MM-DDTHH:mm:ss':
return `${formatter(date, 'YYYY-MM-DD')}T${formatter(date, 'HH:mm:ss')}`;
case 'YYYY-MM-DD HH:mm':
return `${formatter(date, 'YYYY-MM-DD')} ${formatter(date, 'HH:mm')}`;
case 'YYYY-MM-DD HH':
return `${formatter(date, 'YYYY-MM-DD')} ${formatter(date, 'HH')}`;
case 'YYYY-MM-DD':
return formatter(date, template);
case 'YYYYMMDD':
return formatter(date, template);
case 'DD.MM.YYYY':
return formatter(date, template);
case 'YYYY.MM.DD':
return `${formatter(date, 'YYYY.MM.DD')}`;
case 'YYYY.MM.DD HH:mm':
return `${formatter(date, 'YYYY.MM.DD')} ${formatter(date, 'HH:mm')}`;
case 'YYYY.MM.DD HH':
return `${formatter(date, 'YYYY.MM.DD')} ${formatter(date, 'HH')}`;
case 'YYYY.MM.DD HH:mm:ss':
return `${formatter(date, 'YYYY.MM.DD')} ${formatter(date, 'HH:mm:ss')}`;
case 'DD-MM-YYYY HH:mm:ss':
return `${formatter(date, 'DD-MM-YYYY')} ${formatter(date, 'HH:mm:ss')}`;
case 'DD-MM-YYYY HH:mm':
return `${formatter(date, 'DD-MM-YYYY')} ${formatter(date, 'HH:mm')}`;
case 'DD-MM-YYYY HH':
return `${formatter(date, 'DD-MM-YYYY')} ${formatter(date, 'HH')}`;
case 'DD-MM-YYYY':
return `${formatter(date, 'DD-MM-YYYY')}`;
case 'DD.MM.YYYY HH:mm:ss':
return `${formatter(date, 'DD.MM.YYYY')} ${formatter(date, 'HH:mm:ss')}`;
case 'DD.MM.YYYY HH:mm':
return `${formatter(date, 'DD.MM.YYYY')} ${formatter(date, 'HH:mm')}`;
case 'dddd':
return formatter(date, template);
case 'HH:mm:ss':
return `${formatter(date, template)}`;
case 'HH:mm':
return `${formatter(date, template)}`;
case 'X':
return formatter(date, template);
case 'x':
return formatter(date, template);
default:
return formatter(date, template);
}
}
/**
*
* @param {number} number
* @returns {number}
*/
function absFloor(number) {
if (number < 0) {
return Math.ceil(number) || 0;
}
return Math.floor(number);
}
/**
*
* @param {string|Date|KkDate} start
* @param {string|Date|KkDate} end
* @param {'seconds'|'minutes'|'hours'|'days'|'months'|'years'} type - The unit of time type
* @param {boolean} is_decimal
* @returns {object}
*/
function diff(start, end, type, is_decimal = false, turn_difftime = false) {
const startDate = start.getTime();
const endDate = new KkDate(end).getTime();
let type_value = null;
switch (type) {
case 'seconds':
type_value = 1;
break;
case 'minutes':
type_value = 60;
break;
case 'hours':
type_value = 3600;
break;
case 'days':
type_value = 86400;
break;
case 'months':
type_value = 2629800;
break;
case 'years':
type_value = 31557600;
break;
default:
throw new Error('invalid type for diff');
}
const diffTime_value = (endDate - startDate) / 1000 / type_value;
if (turn_difftime) {
return is_decimal ? diffTime_value : absFloor(diffTime_value);
}
return {
type_value,
diffTime: is_decimal ? diffTime_value : absFloor(diffTime_value),
};
}
/**
*
* @param {Date} this.date
* @param {string} template
* @returns {string}
*/
function formatter(orj_this, template = null) {
isInvalid(orj_this.date);
if (template === 'X') {
return parseInt(orj_this.date.valueOf() / 1000, 10);
}
if (template === 'x') {
return parseInt(orj_this.date.valueOf(), 10);
}
const year = orj_this.date.getFullYear();
const month = String(orj_this.date.getMonth() + 1).padStart(2, '0'); // Aylar 0-11 arası olduğu için +1 ekliyoruz
const day = String(orj_this.date.getDate()).padStart(2, '0');
const minutes = String(orj_this.date.getMinutes()).padStart(2, '0');
const seconds = String(orj_this.date.getSeconds()).padStart(2, '0');
const hours = String(orj_this.date.getHours()).padStart(2, '0');
if (!orj_this.temp_config) {
orj_this.temp_config = {};
}
const locale = orj_this.temp_config.locales || global_config.locales;
switch (template) {
case format_types.dddd:
if (!orj_this.temp_config) {
orj_this.temp_config = {};
}
return orj_this.date.toLocaleString(
orj_this.temp_config.locales || global_config.locales,
orj_this.temp_config.options || global_config.options,
);
case format_types.DD:
return day;
case format_types.MM:
return month;
case format_types['DD-MM-YYYY']:
return `${day}-${month}-${year}`;
case format_types['DD.MM.YYYY']:
return `${day}.${month}.${year}`;
case format_types['YYYY-MM-DD']:
return `${year}-${month}-${day}`;
case format_types['YYYY.MM.DD']:
return `${year}.${month}.${day}`;
case format_types['YYYYMMDD']:
return `${year}${month}${day}`;
case format_types.YYYY:
return `${year}`;
case format_types['HH:mm:ss']: {
return `${hours}:${minutes}:${seconds}`;
}
case format_types['HH:mm']: {
return `${hours}:${minutes}`;
}
case format_types.mm: {
return `${minutes}`;
}