-
-
Notifications
You must be signed in to change notification settings - Fork 824
/
Copy pathDate.php
2480 lines (2266 loc) · 77.2 KB
/
Date.php
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
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
/**
* Date utilties
*/
class CRM_Utils_Date {
/**
* Date input formats.
*
* For example a user selecting `DATE_dd_mm_yyyy` in the context of an import is
* saying that they want the dates they are importing to be converted from dd_mm_yyy format.
*/
public const DATE_yyyy_mm_dd = 1, DATE_mm_dd_yy = 2, DATE_mm_dd_yyyy = 4, DATE_Month_dd_yyyy = 8, DATE_dd_mon_yy = 16, DATE_dd_mm_yyyy = 32;
/**
* Format a date by padding it with leading '0'.
*
* @param array $date
* ('Y', 'M', 'd').
* @param string $separator
* The separator to use when formatting the date.
* @param int|string $invalidDate what to return if the date is invalid
*
* @return string
* formatted string for date
*/
public static function format($date, $separator = '', $invalidDate = 0) {
if (is_numeric($date) &&
((strlen($date) == 8) || (strlen($date) == 14))
) {
return $date;
}
if (!is_array($date) ||
CRM_Utils_System::isNull($date) ||
empty($date['Y'])
) {
return $invalidDate;
}
$date['Y'] = (int ) $date['Y'];
if ($date['Y'] < 1000 || $date['Y'] > 2999) {
return $invalidDate;
}
if (array_key_exists('m', $date)) {
$date['M'] = $date['m'];
}
elseif (array_key_exists('F', $date)) {
$date['M'] = $date['F'];
}
if (!empty($date['M'])) {
$date['M'] = (int ) $date['M'];
if ($date['M'] < 1 || $date['M'] > 12) {
return $invalidDate;
}
}
else {
$date['M'] = 1;
}
if (!empty($date['d'])) {
$date['d'] = (int ) $date['d'];
}
else {
$date['d'] = 1;
}
if (!checkdate($date['M'], $date['d'], $date['Y'])) {
return $invalidDate;
}
$date['M'] = sprintf('%02d', $date['M']);
$date['d'] = sprintf('%02d', $date['d']);
$time = '';
if (!empty($date['H']) ||
!empty($date['h']) ||
!empty($date['i']) ||
!empty($date['s'])
) {
// we have time too..
if (!empty($date['h'])) {
if (($date['A'] ?? NULL) == 'PM' or ($date['a'] ?? NULL) == 'pm') {
if ($date['h'] != 12) {
$date['h'] = $date['h'] + 12;
}
}
if ((($date['A'] ?? NULL) == 'AM' or ($date['a'] ?? NULL) == 'am') &&
($date['h'] ?? NULL) == 12
) {
$date['h'] = '00';
}
$date['h'] = (int ) $date['h'];
}
else {
$date['h'] = 0;
}
// in 24-hour format the hour is under the 'H' key
if (!empty($date['H'])) {
$date['H'] = (int) $date['H'];
}
else {
$date['H'] = 0;
}
if (!empty($date['i'])) {
$date['i'] = (int ) $date['i'];
}
else {
$date['i'] = 0;
}
if ($date['h'] == 0 && $date['H'] != 0) {
$date['h'] = $date['H'];
}
if (!empty($date['s'])) {
$date['s'] = (int ) $date['s'];
}
else {
$date['s'] = 0;
}
$date['h'] = sprintf('%02d', $date['h']);
$date['i'] = sprintf('%02d', $date['i']);
$date['s'] = sprintf('%02d', $date['s']);
if ($separator) {
$time = ' ';
}
$time .= $date['h'] . $separator . $date['i'] . $separator . $date['s'];
}
return $date['Y'] . $separator . $date['M'] . $separator . $date['d'] . $time;
}
/**
* Return abbreviated weekday names according to the locale.
*
* Array will be in localized order according to 'weekBegins' setting,
* but array keys will always match to:
* 0 => Sun
* 1 => Mon
* etc.
*
* @return array
* 0-based array with abbreviated weekday names
*
*/
public static function getAbbrWeekdayNames(): array {
$key = 'abbrDays_' . \CRM_Core_I18n::getLocale();
if (empty(\Civi::$statics[__CLASS__][$key])) {
$intl_formatter = IntlDateFormatter::create(CRM_Core_I18n::getLocale(), IntlDateFormatter::MEDIUM, IntlDateFormatter::MEDIUM, NULL, IntlDateFormatter::GREGORIAN, 'E');
$days = [
0 => $intl_formatter->format(strtotime('Sunday')),
1 => $intl_formatter->format(strtotime('Monday')),
2 => $intl_formatter->format(strtotime('Tuesday')),
3 => $intl_formatter->format(strtotime('Wednesday')),
4 => $intl_formatter->format(strtotime('Thursday')),
5 => $intl_formatter->format(strtotime('Friday')),
6 => $intl_formatter->format(strtotime('Saturday')),
];
// First day of the week
$firstDay = Civi::settings()->get('weekBegins');
\Civi::$statics[__CLASS__][$key] = [];
for ($i = $firstDay; count(\Civi::$statics[__CLASS__][$key]) < 7; $i = $i > 5 ? 0 : $i + 1) {
\Civi::$statics[__CLASS__][$key][$i] = $days[$i];
}
}
return \Civi::$statics[__CLASS__][$key];
}
/**
* Return full weekday names according to the locale.
*
* Array will be in localized order according to 'weekBegins' setting,
* but array keys will always match to:
* 0 => Sunday
* 1 => Monday
* etc.
*
* @return array
* 0-based array with full weekday names
*
*/
public static function getFullWeekdayNames(): array {
$key = 'fullDays_' . \CRM_Core_I18n::getLocale();
if (empty(\Civi::$statics[__CLASS__][$key])) {
$intl_formatter = IntlDateFormatter::create(CRM_Core_I18n::getLocale(), IntlDateFormatter::MEDIUM, IntlDateFormatter::MEDIUM, NULL, IntlDateFormatter::GREGORIAN, 'EEEE');
$days = [
0 => $intl_formatter->format(strtotime('Sunday')),
1 => $intl_formatter->format(strtotime('Monday')),
2 => $intl_formatter->format(strtotime('Tuesday')),
3 => $intl_formatter->format(strtotime('Wednesday')),
4 => $intl_formatter->format(strtotime('Thursday')),
5 => $intl_formatter->format(strtotime('Friday')),
6 => $intl_formatter->format(strtotime('Saturday')),
];
// First day of the week
$firstDay = Civi::settings()->get('weekBegins');
\Civi::$statics[__CLASS__][$key] = [];
for ($i = $firstDay; count(\Civi::$statics[__CLASS__][$key]) < 7; $i = $i > 5 ? 0 : $i + 1) {
\Civi::$statics[__CLASS__][$key][$i] = $days[$i];
}
}
return \Civi::$statics[__CLASS__][$key];
}
/**
* Get the available input formats.
*
* These are the formats that this class is able to convert into a standard format
* provided it knows the input format. These are used when doing an import.
*
* @param bool $isShowTime
*
* @return array
*/
public static function getAvailableInputFormats(bool $isShowTime): array {
if ($isShowTime) {
$dateText = ts('yyyy-mm-dd OR yyyy-mm-dd HH:mm OR yyyymmdd OR yyyymmdd HH:mm (1998-12-25 OR 1998-12-25 15:33 OR 19981225 OR 19981225 10:30 OR ( 2008-9-1 OR 2008-9-1 15:33 OR 20080901 15:33)');
}
else {
$dateText = ts('yyyy-mm-dd OR yyyymmdd (1998-12-25 OR 19981225) OR (2008-9-1 OR 20080901)');
}
return [
CRM_Utils_Date::DATE_yyyy_mm_dd => $dateText,
CRM_Utils_Date::DATE_mm_dd_yy => ts('mm/dd/yy OR mm-dd-yy (12/25/98 OR 12-25-98) OR (9/1/08 OR 9-1-08)'),
CRM_Utils_Date::DATE_mm_dd_yyyy => ts('mm/dd/yyyy OR mm-dd-yyyy (12/25/1998 OR 12-25-1998) OR (9/1/2008 OR 9-1-2008)'),
CRM_Utils_Date::DATE_Month_dd_yyyy => ts('Month dd, yyyy (December 12, 1998)'),
CRM_Utils_Date::DATE_dd_mon_yy => ts('dd-mon-yy OR dd/mm/yy (25-Dec-98 OR 25/12/98 OR 1-09-98)'),
CRM_Utils_Date::DATE_dd_mm_yyyy => ts('dd/mm/yyyy (25/12/1998 OR 1/9/2008 OR 1-Sep-2008 or 25.12.1998 or 25-12-1998)'),
];
}
/**
* Return abbreviated month names according to the locale.
*
* @param bool|string $month (deprecated)
*
* @return array|string
* 1-based array with abbreviated month names
*/
public static function getAbbrMonthNames($month = FALSE) {
$key = 'abbrMonthNames_' . \CRM_Core_I18n::getLocale();
if (empty(\Civi::$statics[__CLASS__][$key])) {
// Note: IntlDateFormatter provides even more strings than `strftime()` or `l10n/*/civicrm.mo`.
// Note: Consistently use UTC for all requests in resolving these names. Avoid edge-cases where TZ support is inconsistent.
$intlFormatter = IntlDateFormatter::create(CRM_Core_I18n::getLocale(), IntlDateFormatter::MEDIUM, IntlDateFormatter::MEDIUM, 'UTC', IntlDateFormatter::GREGORIAN, 'MMM');
$monthNums = range(1, 12);
\Civi::$statics[__CLASS__][$key] = array_combine($monthNums, array_map(
function(int $monthNum) use ($intlFormatter) {
return $intlFormatter->format(gmmktime(0, 0, 0, $monthNum, 1));
},
$monthNums
));
}
if ($month) {
CRM_Core_Error::deprecatedWarning('passing in month is deprecated');
return \Civi::$statics[__CLASS__][$key][$month];
}
return \Civi::$statics[__CLASS__][$key];
}
/**
* Return full month names according to the locale.
*
* @return array
* 1-based array with full month names
*
*/
public static function getFullMonthNames(): array {
$key = 'fullMonthNames_' . \CRM_Core_I18n::getLocale();
if (empty(\Civi::$statics[__CLASS__][$key])) {
// Note: IntlDateFormatter provides even more strings than `strftime()` or `l10n/*/civicrm.mo`.
// Note: Consistently use UTC for all requests in resolving these names. Avoid edge-cases where TZ support is inconsistent.
$intlFormatter = IntlDateFormatter::create(CRM_Core_I18n::getLocale(), IntlDateFormatter::MEDIUM, IntlDateFormatter::MEDIUM, 'UTC', IntlDateFormatter::GREGORIAN, 'MMMM');
$monthNums = range(1, 12);
\Civi::$statics[__CLASS__][$key] = array_combine($monthNums, array_map(
function(int $monthNum) use ($intlFormatter) {
return $intlFormatter->format(gmmktime(0, 0, 0, $monthNum, 1));
},
$monthNums
));
}
return \Civi::$statics[__CLASS__][$key];
}
/**
* @param string $string
*
* @return int
*/
public static function unixTime($string) {
if (!$string) {
return 0;
}
$parsedDate = date_parse($string);
return mktime($parsedDate['hour'],
$parsedDate['minute'],
59,
$parsedDate['month'],
$parsedDate['day'],
$parsedDate['year']
);
}
/**
* Create a date and time string in a provided format.
* %A - Full day name ('Saturday'..'Sunday')
* %a - abbreviated day name ('Sat'..'Sun')
* %b - abbreviated month name ('Jan'..'Dec')
* %B - full month name ('January'..'December')
* %d - day of the month as a decimal number, 0-padded ('01'..'31')
* %e - day of the month as a decimal number, blank-padded (' 1'..'31')
* %E - day of the month as a decimal number ('1'..'31')
* %f - English ordinal suffix for the day of the month ('st', 'nd', 'rd', 'th')
* %H - hour in 24-hour format, 0-padded ('00'..'23')
* %I - hour in 12-hour format, 0-padded ('01'..'12')
* %k - hour in 24-hour format, blank-padded (' 0'..'23')
* %l - hour in 12-hour format, blank-padded (' 1'..'12')
* %m - month as a decimal number, 0-padded ('01'..'12')
* %M - minute, 0-padded ('00'..'60')
* %p - lowercase ante/post meridiem ('am', 'pm')
* %P - uppercase ante/post meridiem ('AM', 'PM')
* %Y - year as a decimal number including the century ('2005')
*
* @param string $dateString
* Date and time in 'YYYY-MM-DD hh:mm:ss' format.
* @param string $format
* The output format.
* @param array $dateParts
* An array with the desired date parts.
*
* @return string
* the $format-formatted $date
*/
public static function customFormat($dateString, $format = NULL, $dateParts = NULL) {
// 1-based (January) month names arrays
$abbrMonths = self::getAbbrMonthNames();
$fullMonths = self::getFullMonthNames();
$fullWeekdayNames = self::getFullWeekdayNames();
$abbrWeekdayNames = self::getAbbrWeekdayNames();
// backwards compatibility with %D being the equivalent of %m/%d/%y
$format = str_replace('%D', '%m/%d/%y', ($format ?? ''));
if (!$format) {
$config = CRM_Core_Config::singleton();
if ($dateParts) {
if (array_intersect(['h', 'H'], $dateParts)) {
$format = $config->dateformatDatetime;
}
elseif (array_intersect(['d', 'j'], $dateParts)) {
$format = $config->dateformatFull;
}
elseif (array_intersect(['m', 'M'], $dateParts)) {
$format = $config->dateformatPartial;
}
else {
$format = $config->dateformatYear;
}
}
else {
if (strpos(($dateString ?? ''), '-')) {
$month = (int) substr($dateString, 5, 2);
$day = (int) substr($dateString, 8, 2);
}
else {
$month = (int) substr(($dateString ?? ''), 4, 2);
$day = (int) substr(($dateString ?? ''), 6, 2);
}
if (strlen(($dateString ?? '')) > 10) {
$format = $config->dateformatDatetime;
}
elseif ($day > 0) {
$format = $config->dateformatFull;
}
elseif ($month > 0) {
$format = $config->dateformatPartial;
}
else {
$format = $config->dateformatYear;
}
}
}
if (!CRM_Utils_System::isNull($dateString)) {
if (strpos($dateString, '-')) {
$year = (int) substr($dateString, 0, 4);
$month = (int) substr($dateString, 5, 2);
$day = (int) substr($dateString, 8, 2);
$hour24 = (int) substr($dateString, 11, 2);
$minute = (int) substr($dateString, 14, 2);
$second = (int) substr($dateString, 17, 2);
}
else {
$year = (int) substr($dateString, 0, 4);
$month = (int) substr($dateString, 4, 2);
$day = (int) substr($dateString, 6, 2);
$hour24 = (int) substr($dateString, 8, 2);
$minute = (int) substr($dateString, 10, 2);
$second = (int) substr($dateString, 12, 2);
}
$dayInt = date('w', strtotime($dateString));
if ($day % 10 == 1 and $day != 11) {
$suffix = 'st';
}
elseif ($day % 10 == 2 and $day != 12) {
$suffix = 'nd';
}
elseif ($day % 10 == 3 and $day != 13) {
$suffix = 'rd';
}
else {
$suffix = 'th';
}
if ($hour24 < 12) {
if ($hour24 == 00) {
$hour12 = 12;
}
else {
$hour12 = $hour24;
}
$type = 'AM';
}
else {
if ($hour24 == 12) {
$hour12 = 12;
}
else {
$hour12 = $hour24 - 12;
}
$type = 'PM';
}
$date = [
'%A' => $fullWeekdayNames[$dayInt] ?? NULL,
'%a' => $abbrWeekdayNames[$dayInt] ?? NULL,
'%b' => $abbrMonths[$month] ?? NULL,
'%B' => $fullMonths[$month] ?? NULL,
'%d' => $day > 9 ? $day : '0' . $day,
'%e' => $day > 9 ? $day : ' ' . $day,
'%E' => $day,
'%f' => $suffix,
'%H' => $hour24 > 9 ? $hour24 : '0' . $hour24,
'%h' => $hour12 > 9 ? $hour12 : '0' . $hour12,
'%I' => $hour12 > 9 ? $hour12 : '0' . $hour12,
'%k' => $hour24 > 9 ? $hour24 : ' ' . $hour24,
'%l' => $hour12 > 9 ? $hour12 : ' ' . $hour12,
'%m' => $month > 9 ? $month : '0' . $month,
'%M' => $minute > 9 ? $minute : '0' . $minute,
'%i' => $minute > 9 ? $minute : '0' . $minute,
'%p' => strtolower($type),
'%P' => $type,
'%Y' => $year,
'%y' => substr($year, 2),
'%s' => str_pad($second, 2, 0, STR_PAD_LEFT),
'%S' => str_pad($second, 2, 0, STR_PAD_LEFT),
'%Z' => date('T', strtotime($dateString)),
];
return strtr($format, $date);
}
return '';
}
/**
* Format the field according to the site's preferred date format.
*
* This is likely to look something like December 31st, 2020.
*
* @param string $date
*
* @return string
*/
public static function formatDateOnlyLong(string $date):string {
return CRM_Utils_Date::customFormat($date, Civi::settings()->get('dateformatFull'));
}
/**
* Wrapper for customFormat that takes a timestamp
*
* @param int $timestamp
* Date and time in timestamp format.
* @param string $format
* The output format.
* @param array $dateParts
* An array with the desired date parts.
*
* @return string
* the $format-formatted $date
*/
public static function customFormatTs($timestamp, $format = NULL, $dateParts = NULL) {
return CRM_Utils_Date::customFormat(date("Y-m-d H:i:s", $timestamp), $format, $dateParts);
}
/**
* Converts the date/datetime from MySQL format to ISO format
*
* @param string $mysql
* Date/datetime in MySQL format.
*
* @return string
* date/datetime in ISO format
*/
public static function mysqlToIso($mysql) {
$year = substr(($mysql ?? ''), 0, 4);
$month = substr(($mysql ?? ''), 4, 2);
$day = substr(($mysql ?? ''), 6, 2);
$hour = substr(($mysql ?? ''), 8, 2);
$minute = substr(($mysql ?? ''), 10, 2);
$second = substr(($mysql ?? ''), 12, 2);
$iso = '';
if ($year) {
$iso .= "$year";
}
if ($month) {
$iso .= "-$month";
if ($day) {
$iso .= "-$day";
}
}
if ($hour) {
$iso .= " $hour";
if ($minute) {
$iso .= ":$minute";
if ($second) {
$iso .= ":$second";
}
}
}
return $iso;
}
/**
* Converts the date/datetime from ISO format to MySQL format
* Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was
* used to update an object with a date field was used. The DAO now checks for a '-' in date field strings
* & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
*
* @param string $iso
* Date/datetime in ISO format.
*
* @return string
* date/datetime in MySQL format
*/
public static function isoToMysql($iso) {
$dropArray = ['-' => '', ':' => '', ' ' => ''];
return strtr(($iso ?? ''), $dropArray);
}
/**
* Converts the any given date to default date format.
*
* @param array $params
* Has given date-format.
* @param int $dateType
* Type of date.
* @param string $dateParam
* Index of params.
*
* @deprecated since 5.70 will be removed around 5.80.
*
* At time of deprecation only usages were in CiviHR & CiviProspect in classes that
* appeared to be otherwise unmaintained & broken.
*
* @return bool
*/
public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
CRM_Core_Error::deprecatedFunctionWarning('no alternative');
$now = getdate();
$value = '';
if (!empty($params[$dateParam])) {
// suppress hh:mm or hh:mm:ss if it exists CRM-7957
$value = preg_replace(self::getTimeRegex(), "", $params[$dateParam]);
}
if (!self::validateDateInput($params[$dateParam] ?? '', $dateType)) {
return FALSE;
}
if ($dateType === self::DATE_yyyy_mm_dd) {
$formattedDate = explode("-", $value);
if (count($formattedDate) == 3) {
$year = (int) $formattedDate[0];
$month = (int) $formattedDate[1];
$day = (int) $formattedDate[2];
}
elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
return TRUE;
}
else {
return FALSE;
}
}
if ($dateType === self::DATE_mm_dd_yy || $dateType === self::DATE_mm_dd_yyyy) {
$formattedDate = explode("/", $value);
if (count($formattedDate) != 3) {
$formattedDate = explode("-", $value);
}
if (count($formattedDate) == 3) {
$year = (int) $formattedDate[2];
$month = (int) $formattedDate[0];
$day = (int) $formattedDate[1];
}
else {
return FALSE;
}
}
if ($dateType === self::DATE_Month_dd_yyyy) {
$dateArray = explode(' ', $value);
// ignore comma(,)
$dateArray[1] = (int) substr($dateArray[1], 0, 2);
$monthInt = 0;
$fullMonths = self::getFullMonthNames();
foreach ($fullMonths as $key => $val) {
if (strtolower($dateArray[0]) == strtolower($val)) {
$monthInt = $key;
break;
}
}
if (!$monthInt) {
$abbrMonths = self::getAbbrMonthNames();
foreach ($abbrMonths as $key => $val) {
if (strtolower(trim($dateArray[0], ".")) == strtolower($val)) {
$monthInt = $key;
break;
}
}
}
$year = (int) $dateArray[2];
$day = (int) $dateArray[1];
$month = (int) $monthInt;
}
if ($dateType === self::DATE_dd_mon_yy) {
$dateArray = explode('-', $value);
if (count($dateArray) != 3) {
$dateArray = explode('/', $value);
}
if (count($dateArray) == 3) {
$monthInt = 0;
$fullMonths = self::getFullMonthNames();
foreach ($fullMonths as $key => $val) {
if (strtolower($dateArray[1]) == strtolower($val)) {
$monthInt = $key;
break;
}
}
if (!$monthInt) {
$abbrMonths = self::getAbbrMonthNames();
foreach ($abbrMonths as $key => $val) {
if (strtolower(trim($dateArray[1], ".")) == strtolower($val)) {
$monthInt = $key;
break;
}
}
}
if (!$monthInt) {
$monthInt = $dateArray[1];
}
$year = (int) $dateArray[2];
$day = (int) $dateArray[0];
$month = (int) $monthInt;
}
else {
return FALSE;
}
}
if ($dateType === self::DATE_dd_mm_yyyy) {
$formattedDate = explode("/", $value);
if (count($formattedDate) == 3) {
$year = (int) $formattedDate[2];
$month = (int) $formattedDate[1];
$day = (int) $formattedDate[0];
}
else {
return FALSE;
}
}
$month = ($month < 10) ? "0" . "$month" : $month;
$day = ($day < 10) ? "0" . "$day" : $day;
$year = (int) $year;
if ($year < 100) {
$year = substr($now['year'], 0, 2) * 100 + $year;
if ($year > ($now['year'] + 5)) {
$year = $year - 100;
}
elseif ($year <= ($now['year'] - 95)) {
$year = $year + 100;
}
}
if ($params[$dateParam]) {
$params[$dateParam] = "$year$month$day";
}
// if month is invalid return as error
if ($month !== '00' && $month <= 12) {
return TRUE;
}
return FALSE;
}
/**
* Validate input date against the input type.
*
* @param string $inputValue
* @param int $dateType
*
* @internal Function signature subject to change without notice.
*
* @return bool
*/
protected static function validateDateInput(string $inputValue, int $dateType = self::DATE_yyyy_mm_dd): bool {
// @todo - return these regex from the same function that returns the values in getAvailableInputFormats()
// so they are defined together.
// suppress hh:mm or hh:mm:ss if it exists CRM-7957
// @todo - fix regex instead.
$inputValue = preg_replace(self::getTimeRegex(), "", $inputValue);
switch ($dateType) {
case self::DATE_yyyy_mm_dd:
// 4 numbers separated by - followed by 1-2 numbers, separated by -
// followed by 1-2 numbers with optional time string.
return preg_match('/^\d\d\d\d-?(\d|\d\d)-?(\d|\d\d)$/', $inputValue);
case self::DATE_mm_dd_yy:
return preg_match('/^(\d|\d\d)[-\/.](\d|\d\d)[-\/.]\d\d$/', $inputValue);
case self::DATE_mm_dd_yyyy:
return preg_match('/^(\d|\d\d)[-\/.](\d|\d\d)[-\/,]\d\d\d\d$/', $inputValue);
case self::DATE_Month_dd_yyyy:
$monthRegex = self::getMonthRegex();
$regex = '/^' . $monthRegex . ',?\s?(\d|\d\d),?\s]?(\d\d|\d\d\d\d)$/i';
return preg_match($regex, $inputValue);
case self::DATE_dd_mon_yy:
return preg_match('/^(\d|\d\d)-' . self::getMonthRegex() . '-\d\d$/i', $inputValue) || preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d$/', $inputValue);
case self::DATE_dd_mm_yyyy:
return preg_match('/^(\d|\d\d)[-\/.](\d|\d\d)[-\/.]\d\d\d\d/', $inputValue);
}
return FALSE;
}
/**
* Get the regex to extract the time portion.
*
* @internal
*
* @return string
*/
protected static function getTimeRegex(): string {
return "/(\s(([01]*\d)|[2][0-3])(:([0-5]\d)){1,2})$/";
}
/**
* Translate a TTL to a concrete expiration time.
*
* @param null|int|DateInterval $ttl
* @param int $default
* The value to use if $ttl is not specified (NULL).
* @return int
* Timestamp (seconds since epoch).
* @throws \CRM_Utils_Cache_InvalidArgumentException
*/
public static function convertCacheTtlToExpires($ttl, $default) {
if ($ttl === NULL) {
$ttl = $default;
}
if (is_int($ttl)) {
return time() + $ttl;
}
elseif ($ttl instanceof DateInterval) {
return date_add(new DateTime(), $ttl)->getTimestamp();
}
else {
throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
}
}
/**
* Normalize a TTL.
*
* @param null|int|DateInterval $ttl
* @param int $default
* The value to use if $ttl is not specified (NULL).
* @return int
* Seconds until expiration.
* @throws \CRM_Utils_Cache_InvalidArgumentException
*/
public static function convertCacheTtl($ttl, $default) {
if ($ttl === NULL) {
return $default;
}
elseif (is_int($ttl)) {
return $ttl;
}
elseif ($ttl instanceof DateInterval) {
return date_add(new DateTime(), $ttl)->getTimestamp() - time();
}
else {
throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
}
}
/**
* @param int|false|null $timeStamp
*
* @return bool|string
*/
public static function currentDBDate($timeStamp = NULL) {
return $timeStamp ? date('YmdHis', $timeStamp) : date('YmdHis');
}
/**
* @param $date
* @param null $now
*
* @return bool
*/
public static function overdue($date, $now = NULL) {
$mysqlDate = self::isoToMysql($date);
if (!$now) {
$now = self::currentDBDate();
}
else {
$now = self::isoToMysql($now);
}
return !(strtotime($mysqlDate) >= strtotime($now));
}
/**
* Get customized today.
*
* This function is used for getting customized today. To get
* actuall today pass 'dayParams' as null. or else pass the day,
* month, year values as array values
* Example: $dayParams = array(
* 'day' => '25', 'month' => '10',
* 'year' => '2007' );
*
* @param array $dayParams of the day, month, year.
* Array of the day, month, year.
* values.
* @param string $format
* Expected date format( default.
* format is 2007-12-21 )
*
* @return string
* Return the customized today's date (Y-m-d)
*/
public static function getToday($dayParams = NULL, $format = "Y-m-d") {
if (is_null($dayParams) || empty($dayParams)) {
$today = date($format);
}
else {
$today = date($format, mktime(0, 0, 0,
$dayParams['month'],
$dayParams['day'],
$dayParams['year']
));
}
return $today;
}
/**
* Find whether today's date lies in
* the given range
*
* @param Date $startDate
* Start date for the range.
* @param Date $endDate
* End date for the range.
*
* @return bool
* true if today's date is in the given date range
*/
public static function getRange($startDate, $endDate) {
$today = date("Y-m-d");
$mysqlStartDate = self::isoToMysql($startDate);
$mysqlEndDate = self::isoToMysql($endDate);
$mysqlToday = self::isoToMysql($today);
if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
return TRUE;
}
elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
return TRUE;
}
elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
return TRUE;
}
return FALSE;
}
/**
* Get start date and end from
* the given relative term and unit
*
* @param string $relative Relative format in the format term.unit.
* Eg: previous.day
*
* @param string $from
* @param string $to
* @param string $fromTime
* @param string $toTime
*
* @return array
* start date, end date
*/
public static function getFromTo($relative, $from = NULL, $to = NULL, $fromTime = NULL, $toTime = '235959') {
if ($relative) {
[$term, $unit] = explode('.', $relative, 2);
$dateRange = self::relativeToAbsolute($term, $unit);
$from = substr(($dateRange['from'] ?? ''), 0, 8);
$to = substr(($dateRange['to'] ?? ''), 0, 8);
// @todo fix relativeToAbsolute & add tests
// relativeToAbsolute returns 8 char date strings
// or 14 char date + time strings.
// We should use those. However, it turns out to be unreliable.
// e.g. this.week does NOT return 235959 for 'from'
// so our defaults are more reliable.
// Currently relativeToAbsolute only supports 'whole' days so that is ok
}
$from = self::processDate($from, $fromTime);
$to = self::processDate($to, $toTime);
return [$from, $to];
}
/**
* Calculate Age in Years if greater than one year else in months.
*
* @param Date $birthDate
* Birth Date.
* @param Date $targetDate
* Target Date. (show age on specific date)
*
* @return array
* array $results contains years or months
*/
public static function calculateAge($birthDate, $targetDate = NULL) {
$results = [];
$formatedBirthDate = CRM_Utils_Date::customFormat($birthDate, '%Y-%m-%d');
$bDate = explode('-', $formatedBirthDate);
$birthYear = $bDate[0];
$birthMonth = $bDate[1];
$birthDay = $bDate[2];
$targetDate = strtotime($targetDate ?? date('Y-m-d'));
$year_diff = date("Y", $targetDate) - $birthYear;
// don't calculate age CRM-3143
if ($birthYear == '1902') {
return $results;
}
switch ($year_diff) {