CRM/Utils add comments
[civicrm-core.git] / CRM / Utils / Date.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * Date utilties
38 */
39class CRM_Utils_Date {
40
41 /**
42 * format a date by padding it with leading '0'.
43 *
f4aaa82a
EM
44 * @param array $date ('Y', 'M', 'd')
45 * @param string $separator the seperator to use when formatting the date
46 * @param int|string $invalidDate what to return if the date is invalid
6a488035
TO
47 *
48 * @return string - formatted string for date
49 *
50 * @static
51 */
52 static function format($date, $separator = '', $invalidDate = 0) {
53 if (is_numeric($date) &&
54 ((strlen($date) == 8) || (strlen($date) == 14))
55 ) {
56 return $date;
57 }
58
59 if (!is_array($date) ||
60 CRM_Utils_System::isNull($date) ||
61 empty($date['Y'])
62 ) {
63 return $invalidDate;
64 }
65
66 $date['Y'] = (int ) $date['Y'];
67 if ($date['Y'] < 1000 || $date['Y'] > 2999) {
68 return $invalidDate;
69 }
70
71 if (array_key_exists('m', $date)) {
72 $date['M'] = $date['m'];
73 }
74 elseif (array_key_exists('F', $date)) {
75 $date['M'] = $date['F'];
76 }
77
a7488080 78 if (!empty($date['M'])) {
6a488035
TO
79 $date['M'] = (int ) $date['M'];
80 if ($date['M'] < 1 || $date['M'] > 12) {
81 return $invalidDate;
82 }
83 }
84 else {
85 $date['M'] = 1;
86 }
87
a7488080 88 if (!empty($date['d'])) {
6a488035
TO
89 $date['d'] = (int ) $date['d'];
90 }
91 else {
92 $date['d'] = 1;
93 }
94
95 if (!checkdate($date['M'], $date['d'], $date['Y'])) {
96 return $invalidDate;
97 }
98
99 $date['M'] = sprintf('%02d', $date['M']);
100 $date['d'] = sprintf('%02d', $date['d']);
101
102 $time = '';
103 if (CRM_Utils_Array::value('H', $date) != NULL ||
104 CRM_Utils_Array::value('h', $date) != NULL ||
105 CRM_Utils_Array::value('i', $date) != NULL ||
106 CRM_Utils_Array::value('s', $date) != NULL
107 ) {
108 // we have time too..
a7488080 109 if (!empty($date['h'])) {
6a488035
TO
110 if (CRM_Utils_Array::value('A', $date) == 'PM' or CRM_Utils_Array::value('a', $date) == 'pm') {
111 if ($date['h'] != 12) {
112 $date['h'] = $date['h'] + 12;
113 }
114 }
115 if ((CRM_Utils_Array::value('A', $date) == 'AM' or CRM_Utils_Array::value('a', $date) == 'am') &&
116 CRM_Utils_Array::value('h', $date) == 12
117 ) {
118 $date['h'] = '00';
119 }
120
121 $date['h'] = (int ) $date['h'];
122 }
123 else {
124 $date['h'] = 0;
125 }
126
127 // in 24-hour format the hour is under the 'H' key
a7488080 128 if (!empty($date['H'])) {
6a488035
TO
129 $date['H'] = (int) $date['H'];
130 }
131 else {
132 $date['H'] = 0;
133 }
134
a7488080 135 if (!empty($date['i'])) {
6a488035
TO
136 $date['i'] = (int ) $date['i'];
137 }
138 else {
139 $date['i'] = 0;
140 }
141
142 if ($date['h'] == 0 && $date['H'] != 0) {
143 $date['h'] = $date['H'];
144 }
145
a7488080 146 if (!empty($date['s'])) {
6a488035
TO
147 $date['s'] = (int ) $date['s'];
148 }
149 else {
150 $date['s'] = 0;
151 }
152
153 $date['h'] = sprintf('%02d', $date['h']);
154 $date['i'] = sprintf('%02d', $date['i']);
155 $date['s'] = sprintf('%02d', $date['s']);
156
157 if ($separator) {
158 $time = '&nbsp;';
159 }
160 $time .= $date['h'] . $separator . $date['i'] . $separator . $date['s'];
161 }
162
163 return $date['Y'] . $separator . $date['M'] . $separator . $date['d'] . $time;
164 }
165
166 /**
167 * return abbreviated weekday names according to the locale
168 *
169 * @return array 0-based array with abbreviated weekday names
170 *
171 * @static
172 */
173 static function &getAbbrWeekdayNames() {
174 static $abbrWeekdayNames;
175 if (!isset($abbrWeekdayNames)) {
176
177 // set LC_TIME and build the arrays from locale-provided names
178 // June 1st, 1970 was a Monday
179 CRM_Core_I18n::setLcTime();
180 for ($i = 0; $i < 7; $i++) {
181 $abbrWeekdayNames[$i] = strftime('%a', mktime(0, 0, 0, 6, $i, 1970));
182 }
183 }
184 return $abbrWeekdayNames;
185 }
186
187 /**
188 * return full weekday names according to the locale
189 *
190 * @return array 0-based array with full weekday names
191 *
192 * @static
193 */
194 static function &getFullWeekdayNames() {
195 static $fullWeekdayNames;
196 if (!isset($fullWeekdayNames)) {
197
198 // set LC_TIME and build the arrays from locale-provided names
199 // June 1st, 1970 was a Monday
200 CRM_Core_I18n::setLcTime();
201 for ($i = 0; $i < 7; $i++) {
202 $fullWeekdayNames[$i] = strftime('%A', mktime(0, 0, 0, 6, $i, 1970));
203 }
204 }
205 return $fullWeekdayNames;
206 }
207
208 /**
209 * return abbreviated month names according to the locale
210 *
f4aaa82a
EM
211 * @param bool $month
212 *
6a488035
TO
213 * @return array 1-based array with abbreviated month names
214 *
215 * @static
216 */
217 static function &getAbbrMonthNames($month = FALSE) {
218 static $abbrMonthNames;
219 if (!isset($abbrMonthNames)) {
220
221 // set LC_TIME and build the arrays from locale-provided names
222 CRM_Core_I18n::setLcTime();
223 for ($i = 1; $i <= 12; $i++) {
224 $abbrMonthNames[$i] = strftime('%b', mktime(0, 0, 0, $i, 10, 1970));
225 }
226 }
227 if ($month) {
228 return $abbrMonthNames[$month];
229 }
230 return $abbrMonthNames;
231 }
232
233 /**
234 * return full month names according to the locale
235 *
236 * @return array 1-based array with full month names
237 *
238 * @static
239 */
240 static function &getFullMonthNames() {
241 static $fullMonthNames;
242 if (!isset($fullMonthNames)) {
243
244 // set LC_TIME and build the arrays from locale-provided names
245 CRM_Core_I18n::setLcTime();
246 for ($i = 1; $i <= 12; $i++) {
247 $fullMonthNames[$i] = strftime('%B', mktime(0, 0, 0, $i, 10, 1970));
248 }
249 }
250 return $fullMonthNames;
251 }
252
5bc392e6
EM
253 /**
254 * @param $string
255 *
256 * @return int
257 */
6a488035
TO
258 static function unixTime($string) {
259 if (empty($string)) {
260 return 0;
261 }
262 $parsedDate = date_parse($string);
263 return mktime(CRM_Utils_Array::value('hour', $parsedDate),
264 CRM_Utils_Array::value('minute', $parsedDate),
265 59,
266 CRM_Utils_Array::value('month', $parsedDate),
267 CRM_Utils_Array::value('day', $parsedDate),
268 CRM_Utils_Array::value('year', $parsedDate)
269 );
270 }
271
272 /**
273 * create a date and time string in a provided format
274 *
275 * %b - abbreviated month name ('Jan'..'Dec')
276 * %B - full month name ('January'..'December')
277 * %d - day of the month as a decimal number, 0-padded ('01'..'31')
278 * %e - day of the month as a decimal number, blank-padded (' 1'..'31')
279 * %E - day of the month as a decimal number ('1'..'31')
280 * %f - English ordinal suffix for the day of the month ('st', 'nd', 'rd', 'th')
281 * %H - hour in 24-hour format, 0-padded ('00'..'23')
282 * %I - hour in 12-hour format, 0-padded ('01'..'12')
283 * %k - hour in 24-hour format, blank-padded (' 0'..'23')
284 * %l - hour in 12-hour format, blank-padded (' 1'..'12')
285 * %m - month as a decimal number, 0-padded ('01'..'12')
286 * %M - minute, 0-padded ('00'..'60')
287 * %p - lowercase ante/post meridiem ('am', 'pm')
288 * %P - uppercase ante/post meridiem ('AM', 'PM')
289 * %Y - year as a decimal number including the century ('2005')
290 *
f4aaa82a
EM
291 * @param $dateString
292 * @param string $format the output format
293 * @param array $dateParts an array with the desired date parts
6a488035 294 *
f4aaa82a 295 * @internal param string $date date and time in 'YYYY-MM-DD hh:mm:ss' format
6a488035
TO
296 * @return string the $format-formatted $date
297 *
298 * @static
299 */
300 static function customFormat($dateString, $format = NULL, $dateParts = NULL) {
301 // 1-based (January) month names arrays
302 $abbrMonths = self::getAbbrMonthNames();
303 $fullMonths = self::getFullMonthNames();
304
305 if (!$format) {
306 $config = CRM_Core_Config::singleton();
307
308 if ($dateParts) {
309 if (array_intersect(array('h', 'H'), $dateParts)) {
310 $format = $config->dateformatDatetime;
311 }
312 elseif (array_intersect(array('d', 'j'), $dateParts)) {
313 $format = $config->dateformatFull;
314 }
315 elseif (array_intersect(array('m', 'M'), $dateParts)) {
316 $format = $config->dateformatPartial;
317 }
318 else {
319 $format = $config->dateformatYear;
320 }
321 }
322 else {
323 if (strpos($dateString, '-')) {
324 $month = (int) substr($dateString, 5, 2);
325 $day = (int) substr($dateString, 8, 2);
326 }
327 else {
328 $month = (int) substr($dateString, 4, 2);
329 $day = (int) substr($dateString, 6, 2);
330 }
331
332 if (strlen($dateString) > 10) {
333 $format = $config->dateformatDatetime;
334 }
335 elseif ($day > 0) {
336 $format = $config->dateformatFull;
337 }
338 elseif ($month > 0) {
339 $format = $config->dateformatPartial;
340 }
341 else {
342 $format = $config->dateformatYear;
343 }
344 }
345 }
346
347 if ($dateString) {
348 if (strpos($dateString, '-')) {
349 $year = (int) substr($dateString, 0, 4);
350 $month = (int) substr($dateString, 5, 2);
351 $day = (int) substr($dateString, 8, 2);
352
353 $hour24 = (int) substr($dateString, 11, 2);
354 $minute = (int) substr($dateString, 14, 2);
355 }
356 else {
357 $year = (int) substr($dateString, 0, 4);
358 $month = (int) substr($dateString, 4, 2);
359 $day = (int) substr($dateString, 6, 2);
360
361 $hour24 = (int) substr($dateString, 8, 2);
362 $minute = (int) substr($dateString, 10, 2);
363 }
364
365 if ($day % 10 == 1 and $day != 11) {
366 $suffix = 'st';
367 }
368 elseif ($day % 10 == 2 and $day != 12) {
369 $suffix = 'nd';
370 }
371 elseif ($day % 10 == 3 and $day != 13) {
372 $suffix = 'rd';
373 }
374 else {
375 $suffix = 'th';
376 }
377
378 if ($hour24 < 12) {
379 if ($hour24 == 00) {
380 $hour12 = 12;
381 }
382 else {
383 $hour12 = $hour24;
384 }
385 $type = 'AM';
386 }
387 else {
388 if ($hour24 == 12) {
389 $hour12 = 12;
390 }
391 else {
392 $hour12 = $hour24 - 12;
393 }
394 $type = 'PM';
395 }
396
397 $date = array(
398 '%b' => CRM_Utils_Array::value($month, $abbrMonths),
399 '%B' => CRM_Utils_Array::value($month, $fullMonths),
400 '%d' => $day > 9 ? $day : '0' . $day,
401 '%e' => $day > 9 ? $day : ' ' . $day,
402 '%E' => $day,
403 '%f' => $suffix,
404 '%H' => $hour24 > 9 ? $hour24 : '0' . $hour24,
405 '%h' => $hour12 > 9 ? $hour12 : '0' . $hour12,
406 '%I' => $hour12 > 9 ? $hour12 : '0' . $hour12,
407 '%k' => $hour24 > 9 ? $hour24 : ' ' . $hour24,
408 '%l' => $hour12 > 9 ? $hour12 : ' ' . $hour12,
409 '%m' => $month > 9 ? $month : '0' . $month,
410 '%M' => $minute > 9 ? $minute : '0' . $minute,
411 '%i' => $minute > 9 ? $minute : '0' . $minute,
412 '%p' => strtolower($type),
413 '%P' => $type,
414 '%A' => $type,
415 '%Y' => $year,
416 );
417
418 return strtr($format, $date);
419 }
420 else {
421 return '';
422 }
423 }
424
425 /**
426 * converts the date/datetime from MySQL format to ISO format
427 *
428 * @param string $mysql date/datetime in MySQL format
429 *
430 * @return string date/datetime in ISO format
431 * @static
432 */
433 static function mysqlToIso($mysql) {
434 $year = substr($mysql, 0, 4);
435 $month = substr($mysql, 4, 2);
436 $day = substr($mysql, 6, 2);
437 $hour = substr($mysql, 8, 2);
438 $minute = substr($mysql, 10, 2);
439 $second = substr($mysql, 12, 2);
440
441 $iso = '';
442 if ($year) {
443 $iso .= "$year";
444 }
445 if ($month) {
446 $iso .= "-$month";
447 if ($day) {
448 $iso .= "-$day";
449 }
450 }
451
452 if ($hour) {
453 $iso .= " $hour";
454 if ($minute) {
455 $iso .= ":$minute";
456 if ($second) {
457 $iso .= ":$second";
458 }
459 }
460 }
461 return $iso;
462 }
463
464 /**
465 * converts the date/datetime from ISO format to MySQL format
466 *
467 * @param string $iso date/datetime in ISO format
468 *
469 * @return string date/datetime in MySQL format
470 * @static
471 */
472 static function isoToMysql($iso) {
473 $dropArray = array('-' => '', ':' => '', ' ' => '');
474 return strtr($iso, $dropArray);
475 }
476
477 /**
478 * converts the any given date to default date format.
479 *
f4aaa82a
EM
480 * @param array $params has given date-format
481 * @param int $dateType type of date
482 * @param string $dateParam index of params
483 *
484 * @return bool
6a488035
TO
485 * @static
486 */
d4c8a770 487 static function convertToDefaultDate(&$params, $dateType, $dateParam) {
6a488035
TO
488 $now = getDate();
489 $cen = substr($now['year'], 0, 2);
490 $prevCen = $cen - 1;
491
492 $value = NULL;
a7488080 493 if (!empty($params[$dateParam])) {
6a488035
TO
494 // suppress hh:mm or hh:mm:ss if it exists CRM-7957
495 $value = preg_replace("/(\s(([01]\d)|[2][0-3])(:([0-5]\d)){1,2})$/", "", $params[$dateParam]);
496 }
497
498 switch ($dateType) {
499 case 1:
500 if (!preg_match('/^\d\d\d\d-?(\d|\d\d)-?(\d|\d\d)$/', $value)) {
501 return FALSE;
502 }
503 break;
504
505 case 2:
506 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d$/', $value)) {
507 return FALSE;
508 }
509 break;
510
511 case 4:
512 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d$/', $value)) {
513 return FALSE;
514 }
515 break;
516
517 case 8:
518 if (!preg_match('/^[A-Za-z]*.[ \t]?\d\d\,[ \t]?\d\d\d\d$/', $value)) {
519 return FALSE;
520 }
521 break;
522
523 case 16:
524 if (!preg_match('/^\d\d-[A-Za-z]{3}.*-\d\d$/', $value) && !preg_match('/^\d\d[-\/]\d\d[-\/]\d\d$/', $value)) {
525 return FALSE;
526 }
527 break;
528
529 case 32:
530 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d/', $value)) {
531 return FALSE;
532 }
533 break;
534 }
535
536 if ($dateType == 1) {
537 $formattedDate = explode("-", $value);
538 if (count($formattedDate) == 3) {
539 $year = (int) $formattedDate[0];
540 $month = (int) $formattedDate[1];
541 $day = (int) $formattedDate[2];
542 }
543 elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
544 return TRUE;
545 }
546 else {
547 return FALSE;
548 }
549 }
550
551
552 if ($dateType == 2 || $dateType == 4) {
553 $formattedDate = explode("/", $value);
554 if (count($formattedDate) != 3) {
555 $formattedDate = explode("-", $value);
556 }
557 if (count($formattedDate) == 3) {
558 $year = (int) $formattedDate[2];
559 $month = (int) $formattedDate[0];
560 $day = (int) $formattedDate[1];
561 }
562 else {
563 return FALSE;
564 }
565 }
566 if ($dateType == 8) {
567 $dateArray = explode(' ', $value);
568 // ignore comma(,)
569 $dateArray[1] = (int) substr($dateArray[1], 0, 2);
570
571 $monthInt = 0;
572 $fullMonths = self::getFullMonthNames();
573 foreach ($fullMonths as $key => $val) {
574 if (strtolower($dateArray[0]) == strtolower($val)) {
575 $monthInt = $key;
576 break;
577 }
578 }
579 if (!$monthInt) {
580 $abbrMonths = self::getAbbrMonthNames();
581 foreach ($abbrMonths as $key => $val) {
582 if (strtolower(trim($dateArray[0], ".")) == strtolower($val)) {
583 $monthInt = $key;
584 break;
585 }
586 }
587 }
588 $year = (int) $dateArray[2];
589 $day = (int) $dateArray[1];
590 $month = (int) $monthInt;
591 }
592 if ($dateType == 16) {
593 $dateArray = explode('-', $value);
594 if (count($dateArray) != 3) {
595 $dateArray = explode('/', $value);
596 }
597
598 if (count($dateArray) == 3) {
599 $monthInt = 0;
600 $fullMonths = self::getFullMonthNames();
601 foreach ($fullMonths as $key => $val) {
602 if (strtolower($dateArray[1]) == strtolower($val)) {
603 $monthInt = $key;
604 break;
605 }
606 }
607 if (!$monthInt) {
608 $abbrMonths = self::getAbbrMonthNames();
609 foreach ($abbrMonths as $key => $val) {
610 if (strtolower(trim($dateArray[1], ".")) == strtolower($val)) {
611 $monthInt = $key;
612 break;
613 }
614 }
615 }
616 if (!$monthInt) {
617 $monthInt = $dateArray[1];
618 }
619
620 $year = (int) $dateArray[2];
621 $day = (int) $dateArray[0];
622 $month = (int) $monthInt;
623 }
624 else {
625 return FALSE;
626 }
627 }
628 if ($dateType == 32) {
629 $formattedDate = explode("/", $value);
630 if (count($formattedDate) == 3) {
631 $year = (int) $formattedDate[2];
632 $month = (int) $formattedDate[1];
633 $day = (int) $formattedDate[0];
634 }
635 else {
636 return FALSE;
637 }
638 }
639
640 $month = ($month < 10) ? "0" . "$month" : $month;
641 $day = ($day < 10) ? "0" . "$day" : $day;
642
643 $year = (int ) $year;
644 // simple heuristic to determine what century to use
645 // 00 - 20 is always 2000 - 2020
646 // 21 - 99 is always 1921 - 1999
647 if ($year < 21) {
648 $year = (strlen($year) == 1) ? $cen . '0' . $year : $cen . $year;
649 }
650 elseif ($year < 100) {
651 $year = $prevCen . $year;
652 }
653
654 if ($params[$dateParam]) {
655 $params[$dateParam] = "$year$month$day";
656 }
657 //if month is invalid return as error
658 if ($month !== '00' && $month <= 12) {
659 return TRUE;
660 }
661 return FALSE;
662 }
663
5bc392e6
EM
664 /**
665 * @param $date
666 *
667 * @return bool
668 */
6a488035
TO
669 static function isDate(&$date) {
670 if (CRM_Utils_System::isNull($date)) {
671 return FALSE;
672 }
673 return TRUE;
674 }
675
5bc392e6
EM
676 /**
677 * @param null $timeStamp
678 *
679 * @return bool|string
680 */
6a488035
TO
681 static function currentDBDate($timeStamp = NULL) {
682 return $timeStamp ? date('YmdHis', $timeStamp) : date('YmdHis');
683 }
684
5bc392e6
EM
685 /**
686 * @param $date
687 * @param null $now
688 *
689 * @return bool
690 */
6a488035
TO
691 static function overdue($date, $now = NULL) {
692 $mysqlDate = self::isoToMysql($date);
693 if (!$now) {
694 $now = self::currentDBDate();
695 }
696 else {
697 $now = self::isoToMysql($now);
698 }
699
700 return ($mysqlDate >= $now) ? FALSE : TRUE;
701 }
702
703 /**
704 * Function to get customized today
705 *
706 * This function is used for getting customized today. To get
707 * actuall today pass 'dayParams' as null. or else pass the day,
708 * month, year values as array values
709 * Example: $dayParams = array(
710 'day' => '25', 'month' => '10',
711 * 'year' => '2007' );
712 *
713 * @param Array $dayParams Array of the day, month, year
714 * values.
715 * @param string $format expected date format( default
716 * format is 2007-12-21 )
717 *
718 * @return string Return the customized todays date (Y-m-d)
719 * @static
720 */
721 static function getToday($dayParams = NULL, $format = "Y-m-d") {
722 if (is_null($dayParams) || empty($dayParams)) {
723 $today = date($format);
724 }
725 else {
726 $today = date($format, mktime(0, 0, 0,
727 $dayParams['month'],
728 $dayParams['day'],
729 $dayParams['year']
730 ));
731 }
732
733 return $today;
734 }
735
736 /**
737 * Function to find whether today's date lies in
738 * the given range
739 *
740 * @param date $startDate start date for the range
741 * @param date $endDate end date for the range
742 *
743 * @return true todays date is in the given date range
744 * @static
745 */
746 static function getRange($startDate, $endDate) {
747 $today = date("Y-m-d");
748 $mysqlStartDate = self::isoToMysql($startDate);
749 $mysqlEndDate = self::isoToMysql($endDate);
750 $mysqlToday = self::isoToMysql($today);
751
752 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
753 return TRUE;
754 }
755 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
756 return TRUE;
757 }
758 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
759 return TRUE;
760 }
761 return FALSE;
762 }
763
764 /**
765 * Function to get start date and end from
766 * the given relative term and unit
767 *
f4aaa82a
EM
768 * @param date $relative eg: term.unit
769 *
770 * @param $from
771 * @param $to
6a488035
TO
772 *
773 * @return array start date, end date
774 * @static
775 */
776 static function getFromTo($relative, $from, $to) {
777 if ($relative) {
778 list($term, $unit) = explode('.', $relative);
779 $dateRange = self::relativeToAbsolute($term, $unit);
780 $from = $dateRange['from'];
781 //Take only Date Part, Sometime Time part is also present in 'to'
782 $to = substr($dateRange['to'], 0, 8);
783 }
784
785 $from = self::processDate($from);
786 $to = self::processDate($to, '235959');
787
788 return array($from, $to);
789 }
790
791 /**
792 * Function to calculate Age in Years if greater than one year else in months
793 *
794 * @param date $birthDate Birth Date
795 *
796 * @return int array $results contains years or months
797 * @access public
798 * @static
799 */
800 static public function calculateAge($birthDate) {
801 $results = array();
802 $formatedBirthDate = CRM_Utils_Date::customFormat($birthDate, '%Y-%m-%d');
803
804 $bDate = explode('-', $formatedBirthDate);
805 $birthYear = $bDate[0];
806 $birthMonth = $bDate[1];
807 $birthDay = $bDate[2];
808 $year_diff = date("Y") - $birthYear;
809
810 // don't calculate age CRM-3143
811 if ($birthYear == '1902') {
812 return $results;
813 }
814
815 switch ($year_diff) {
816 case 1:
817 $month = (12 - $birthMonth) + date("m");
818 if ($month < 12) {
819 if (date("d") < $birthDay) {
820 $month--;
821 }
822 $results['months'] = $month;
823 }
824 elseif ($month == 12 && (date("d") < $birthDay)) {
825 $results['months'] = $month - 1;
826 }
827 else {
828 $results['years'] = $year_diff;
829 }
830 break;
831
832 case 0:
833 $month = date("m") - $birthMonth;
834 $results['months'] = $month;
835 break;
836
837 default:
838 $results['years'] = $year_diff;
839 if ((date("m") < $birthMonth) || (date("m") == $birthMonth) && (date("d") < $birthDay)) {
840 $results['years']--;
841 }
842 }
843
844 return $results;
845 }
846
847 /**
848 * Function to calculate next payment date according to provided unit & interval
849 *
f4aaa82a 850 * @param string $unit frequency unit like year,month, week etc..
6a488035 851 *
f4aaa82a 852 * @param int $interval frequency interval.
6a488035 853 *
f4aaa82a
EM
854 * @param array $date start date of pledge.
855 *
856 * @param bool $dontCareTime
6a488035
TO
857 *
858 * @return array $result contains new date with added interval
859 * @access public
860 */
861 static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
862 if (is_array($date)) {
863 $hour = CRM_Utils_Array::value('H', $date);
864 $minute = CRM_Utils_Array::value('i', $date);
865 $second = CRM_Utils_Array::value('s', $date);
866 $month = CRM_Utils_Array::value('M', $date);
867 $day = CRM_Utils_Array::value('d', $date);
868 $year = CRM_Utils_Array::value('Y', $date);
869 }
870 else {
871 extract(date_parse($date));
872 }
873 $date = mktime($hour, $minute, $second, $month, $day, $year);
874 switch ($unit) {
875 case 'year':
876 $date = mktime($hour, $minute, $second, $month, $day, $year + $interval);
877 break;
878
879 case 'month':
880 $date = mktime($hour, $minute, $second, $month + $interval, $day, $year);
881 break;
882
883 case 'week':
884 $interval = $interval * 7;
885 $date = mktime($hour, $minute, $second, $month, $day + $interval, $year);
886 break;
887
888 case 'day':
889 $date = mktime($hour, $minute, $second, $month, $day + $interval, $year);
890 break;
891
892 case 'second':
893 $date = mktime($hour, $minute, $second + $interval, $month, $day, $year);
894 break;
895 }
896
897 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
898
899 $date = array();
900 $date['M'] = $scheduleDate[0];
901 $date['d'] = $scheduleDate[1];
902 $date['Y'] = $scheduleDate[2];
903 if ($dontCareTime == FALSE) {
904 $date['H'] = $scheduleDate[3];
905 $date['i'] = $scheduleDate[4];
906 $date['s'] = $scheduleDate[5];
907 }
908 return $date;
909 }
910
911 /**
912 * function to check given format is valid for bith date.
913 * and retrun supportable birth date format w/ qf mapping.
914 *
915 * @param $format given format ( eg 'M Y', 'Y M' )
916 * return array of qfMapping and date parts for date format.
f4aaa82a
EM
917 *
918 * @return array|null|string
6a488035
TO
919 */
920 static function &checkBirthDateFormat($format = NULL) {
921 $birthDateFormat = NULL;
922 if (!$format) {
923 $birthDateFormat = self::getDateFormat('birth');
924 }
925
926 $supportableFormats = array(
927 'mm/dd' => '%B %E%f',
928 'dd-mm' => '%E%f %B',
929 'yy-mm' => '%Y %B',
930 'M yy' => '%b %Y',
931 'yy' => '%Y',
932 'dd/mm/yy' => '%E%f %B %Y',
933 );
934
935 if (array_key_exists($birthDateFormat, $supportableFormats)) {
936 $birthDateFormat = array('qfMapping' => $supportableFormats[$birthDateFormat]);
937 }
938
939 return $birthDateFormat;
940 }
941
942 /**
943 * resolves the given relative time interval into finite time limits
944 *
945 * @param array $relativeTerm relative time frame like this, previous, etc
946 * @param int $unit frequency unit like year, month, week etc..
947 *
948 * @return array $dateRange start date and end date for the relative time frame
949 * @static
950 */
951 static function relativeToAbsolute($relativeTerm, $unit) {
952 $now = getDate();
953 $from = $to = $dateRange = array();
954 $from['H'] = $from['i'] = $from['s'] = 0;
955
956 switch ($unit) {
957 case 'year':
958 switch ($relativeTerm) {
959 case 'this':
960 $from['d'] = $from['M'] = 1;
961 $to['d'] = 31;
962 $to['M'] = 12;
963 $to['Y'] = $from['Y'] = $now['year'];
964 break;
965
966 case 'previous':
967 $from['M'] = $from['d'] = 1;
968 $to['d'] = 31;
969 $to['M'] = 12;
970 $to['Y'] = $from['Y'] = $now['year'] - 1;
971 break;
972
973 case 'previous_before':
974 $from['M'] = $from['d'] = 1;
975 $to['d'] = 31;
976 $to['M'] = 12;
977 $to['Y'] = $from['Y'] = $now['year'] - 2;
978 break;
979
980 case 'previous_2':
981 $from['M'] = $from['d'] = 1;
982 $to['d'] = 31;
983 $to['M'] = 12;
984 $from['Y'] = $now['year'] - 2;
985 $to['Y'] = $now['year'] - 1;
986 break;
987
988 case 'earlier':
989 $to['d'] = 31;
990 $to['M'] = 12;
991 $to['Y'] = $now['year'] - 1;
992 unset($from);
993 break;
994
995 case 'greater':
996 $from['M'] = $from['d'] = 1;
997 $from['Y'] = $now['year'];
998 unset($to);
999 break;
1000
1001 case 'ending':
1002 $to['d'] = $now['mday'];
1003 $to['M'] = $now['mon'];
1004 $to['Y'] = $now['year'];
1005 $to['H'] = 23;
1006 $to['i'] = $to['s'] = 59;
1007 $from = self::intervalAdd('year', -1, $to);
1008 $from = self::intervalAdd('second', 1, $from);
1009 break;
e902edd1 1010
1011 case 'current':
1012 $from['M'] = $from['d'] = 1;
1013 $from['Y'] = $now['year'];
1014 $to['H'] = 23;
1015 $to['i'] = $to['s'] = 59;
1016 $to['d'] = $now['mday'];
1017 $to['M'] = $now['mon'];
1018 $to['Y'] = $now['year'];
1019 break;
e2c3163d 1020
1021 case 'ending_2':
1022 $to['d'] = $now['mday'];
1023 $to['M'] = $now['mon'];
1024 $to['Y'] = $now['year'];
1025 $to['H'] = 23;
1026 $to['i'] = $to['s'] = 59;
1027 $from = self::intervalAdd('year', -2, $to);
1028 $from = self::intervalAdd('second', 1, $from);
1029 break;
1030
1031 case 'ending_3':
1032 $to['d'] = $now['mday'];
1033 $to['M'] = $now['mon'];
1034 $to['Y'] = $now['year'];
1035 $to['H'] = 23;
1036 $to['i'] = $to['s'] = 59;
1037 $from = self::intervalAdd('year', -3, $to);
1038 $from = self::intervalAdd('second', 1, $from);
1039 break;
6a488035
TO
1040 }
1041 break;
1042
1043 case 'fiscal_year':
1044 $config = CRM_Core_Config::singleton();
1045 $from['d'] = $config->fiscalYearStart['d'];
1046 $from['M'] = $config->fiscalYearStart['M'];
1047 $fYear = self::calculateFiscalYear($from['d'], $from['M']);
1048 switch ($relativeTerm) {
1049 case 'this':
1050 $from['Y'] = $fYear;
1051 $fiscalYear = mktime(0, 0, 0, $from['M'], $form['d'], $from['Y'] + 1);
1052 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1053
1054 $to['d'] = $fiscalEnd['2'];
1055 $to['M'] = $fiscalEnd['1'];
1056 $to['Y'] = $fiscalEnd['0'];
1057 break;
1058
1059 case 'previous':
1060 $from['Y'] = $fYear - 1;
1061 $fiscalYear = mktime(0, 0, 0, $from['M'], $form['d'], $from['Y'] + 1);
1062 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1063
1064 $to['d'] = $fiscalEnd['2'];
1065 $to['M'] = $fiscalEnd['1'];
1066 $to['Y'] = $fiscalEnd['0'];
1067 break;
1068 }
1069 break;
1070
1071 case 'quarter':
1072 switch ($relativeTerm) {
1073 case 'this':
1074
1075 $quarter = ceil($now['mon'] / 3);
1076 $from['d'] = 1;
1077 $from['M'] = (3 * $quarter) - 2;
1078 $to['M'] = 3 * $quarter;
1079 $to['Y'] = $from['Y'] = $now['year'];
1080 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1081 break;
1082
1083 case 'previous':
1084 $difference = 1;
1085 $quarter = ceil($now['mon'] / 3);
1086 $quarter = $quarter - $difference;
1087 $subtractYear = 0;
1088 if ($quarter <= 0) {
1089 $subtractYear = 1;
1090 $quarter += 4;
1091 }
1092 $from['d'] = 1;
1093 $from['M'] = (3 * $quarter) - 2;
1094 $to['M'] = 3 * $quarter;
1095 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1096 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1097 break;
1098
1099 case 'previous_before':
1100 $difference = 2;
1101 $quarter = ceil($now['mon'] / 3);
1102 $quarter = $quarter - $difference;
1103 if ($quarter <= 0) {
1104 $subtractYear = 1;
1105 $quarter += 4;
1106 }
1107 $from['d'] = 1;
1108 $from['M'] = (3 * $quarter) - 2;
1109 $to['M'] = 3 * $quarter;
1110 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1111 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1112 break;
1113
1114 case 'previous_2':
1115 $difference = 2;
1116 $quarter = ceil($now['mon'] / 3);
1117 $current_quarter = $quarter;
1118 $quarter = $quarter - $difference;
1119 $subtractYear = 0;
1120 if ($quarter <= 0) {
1121 $subtractYear = 1;
1122 $quarter += 4;
1123 }
1124 $from['d'] = 1;
1125 $from['M'] = (3 * $quarter) - 2;
1126 switch ($current_quarter) {
1127 case 1:
1128 $to['M'] = (4 * $quarter);
1129 break;
1130
1131 case 2:
1132 $to['M'] = (4 * $quarter) + 3;
1133 break;
1134
1135 case 3:
1136 $to['M'] = (4 * $quarter) + 2;
1137 break;
1138
1139 case 4:
1140 $to['M'] = (4 * $quarter) + 1;
1141 break;
1142 }
1143 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1144 if ($to['M'] > 12) {
1145 $to['M'] = 3 * ($quarter - 3);
1146 $to['Y'] = $now['year'];
1147 }
1148 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1149 break;
1150
1151 case 'earlier':
1152 $quarter = ceil($now['mon'] / 3) - 1;
1153 if ($quarter <= 0) {
1154 $subtractYear = 1;
1155 $quarter += 4;
1156 }
1157 $to['M'] = 3 * $quarter;
1158 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1159 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1160 unset($from);
1161 break;
1162
1163 case 'greater':
1164 $quarter = ceil($now['mon'] / 3);
1165 $from['d'] = 1;
1166 $from['M'] = (3 * $quarter) - 2;
1167 $from['Y'] = $now['year'];
1168 unset($to);
1169 break;
1170
1171 case 'ending':
1172 $to['d'] = $now['mday'];
1173 $to['M'] = $now['mon'];
1174 $to['Y'] = $now['year'];
1175 $to['H'] = 23;
1176 $to['i'] = $to['s'] = 59;
1177 $from = self::intervalAdd('month', -3, $to);
1178 $from = self::intervalAdd('second', 1, $from);
1179 break;
e902edd1 1180
1181 case 'current':
1182 $quarter = ceil($now['mon'] / 3);
1183 $from['d'] = 1;
1184 $from['M'] = (3 * $quarter) - 2;
1185 $from['Y'] = $now['year'];
1186 $to['d'] = $now['mday'];
1187 $to['M'] = $now['mon'];
1188 $to['Y'] = $now['year'];
1189 $to['H'] = 23;
1190 $to['i'] = $to['s'] = 59;
1191 break;
6a488035
TO
1192 }
1193 break;
1194
1195 case 'month':
1196 switch ($relativeTerm) {
1197 case 'this':
1198 $from['d'] = 1;
1199 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1200 $from['M'] = $to['M'] = $now['mon'];
1201 $from['Y'] = $to['Y'] = $now['year'];
1202 break;
1203
1204 case 'previous':
1205 $from['d'] = 1;
1206 if ($now['mon'] == 1) {
1207 $from['M'] = $to['M'] = 12;
1208 $from['Y'] = $to['Y'] = $now['year'] - 1;
1209 }
1210 else {
1211 $from['M'] = $to['M'] = $now['mon'] - 1;
1212 $from['Y'] = $to['Y'] = $now['year'];
1213 }
1214 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1215 break;
1216
1217 case 'previous_before':
1218 $from['d'] = 1;
1219 if ($now['mon'] < 3) {
1220 $from['M'] = $to['M'] = 10 + $now['mon'];
1221 $from['Y'] = $to['Y'] = $now['year'] - 1;
1222 }
1223 else {
1224 $from['M'] = $to['M'] = $now['mon'] - 2;
1225 $from['Y'] = $to['Y'] = $now['year'];
1226 }
1227 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1228 break;
1229
1230 case 'previous_2':
1231 $from['d'] = 1;
1232 if ($now['mon'] < 3) {
1233 $from['M'] = 10 + $now['mon'];
1234 $from['Y'] = $now['year'] - 1;
1235 }
1236 else {
1237 $from['M'] = $now['mon'] - 2;
1238 $from['Y'] = $now['year'];
1239 }
1240
1241 if ($now['mon'] == 1) {
1242 $to['M'] = 12;
1243 $to['Y'] = $now['year'] - 1;
1244 }
1245 else {
1246 $to['M'] = $now['mon'] - 1;
1247 $to['Y'] = $now['year'];
1248 }
1249
1250 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1251 break;
1252
1253 case 'earlier':
1254 //before end of past month
1255 if ($now['mon'] == 1) {
1256 $to['M'] = 12;
1257 $to['Y'] = $now['year'] - 1;
1258 }
1259 else {
1260 $to['M'] = $now['mon'] - 1;
1261 $to['Y'] = $now['year'];
1262 }
1263
1264 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1265 unset($from);
1266 break;
1267
1268 case 'greater':
1269 $from['d'] = 1;
1270 $from['M'] = $now['mon'];;
1271 $from['Y'] = $now['year'];
1272 unset($to);
1273 break;
1274
1275 case 'ending':
1276 $to['d'] = $now['mday'];
1277 $to['M'] = $now['mon'];
1278 $to['Y'] = $now['year'];
1279 $to['H'] = 23;
1280 $to['i'] = $to['s'] = 59;
1281 $from = self::intervalAdd('month', -1, $to);
1282 $from = self::intervalAdd('second', 1, $from);
1283 break;
e902edd1 1284
1285 case 'current':
1286 $from['d'] = 1;
1287 $from['M'] = $now['mon'];;
1288 $from['Y'] = $now['year'];
1289 $to['d'] = $now['mday'];
1290 $to['M'] = $now['mon'];
1291 $to['Y'] = $now['year'];
1292 $to['H'] = 23;
1293 $to['i'] = $to['s'] = 59;
1294 break;
6a488035
TO
1295 }
1296 break;
1297
1298 case 'week':
1299 switch ($relativeTerm) {
1300 case 'this':
1301 $from['d'] = $now['mday'];
1302 $from['M'] = $now['mon'];
1303 $from['Y'] = $now['year'];
1304 $from = self::intervalAdd('day', -1 * ($now['wday']), $from);
1305 $to = self::intervalAdd('day', 6, $from);
1306 break;
1307
1308 case 'previous':
1309 $from['d'] = $now['mday'];
1310 $from['M'] = $now['mon'];
1311 $from['Y'] = $now['year'];
1312 $from = self::intervalAdd('day', -1 * ($now['wday']) - 7, $from);
1313 $to = self::intervalAdd('day', 6, $from);
1314 break;
1315
1316 case 'previous_before':
1317 $from['d'] = $now['mday'];
1318 $from['M'] = $now['mon'];
1319 $from['Y'] = $now['year'];
1320 $from = self::intervalAdd('day', -1 * ($now['wday']) - 14, $from);
1321 $to = self::intervalAdd('day', 6, $from);
1322 break;
1323
1324 case 'previous_2':
1325 $from['d'] = $now['mday'];
1326 $from['M'] = $now['mon'];
1327 $from['Y'] = $now['year'];
1328 $from = self::intervalAdd('day', -1 * ($now['wday']) - 14, $from);
1329 $to = self::intervalAdd('day', 13, $from);
1330 break;
1331
1332 case 'earlier':
1333 $to['d'] = $now['mday'];
1334 $to['M'] = $now['mon'];
1335 $to['Y'] = $now['year'];
1336 $to = self::intervalAdd('day', -1 * ($now['wday']) - 1, $to);
1337 unset($from);
1338 break;
1339
1340 case 'greater':
1341 $from['d'] = $now['mday'];
1342 $from['M'] = $now['mon'];
1343 $from['Y'] = $now['year'];
1344 $from = self::intervalAdd('day', -1 * ($now['wday']), $from);
1345 unset($to);
1346 break;
1347
1348 case 'ending':
1349 $to['d'] = $now['mday'];
1350 $to['M'] = $now['mon'];
1351 $to['Y'] = $now['year'];
1352 $to['H'] = 23;
1353 $to['i'] = $to['s'] = 59;
1354 $from = self::intervalAdd('day', -7, $to);
1355 $from = self::intervalAdd('second', 1, $from);
1356 break;
e902edd1 1357
1358 case 'current':
1359 $from['d'] = $now['mday'];
1360 $from['M'] = $now['mon'];
1361 $from['Y'] = $now['year'];
1362 $from = self::intervalAdd('day', -1 * ($now['wday']), $from);
1363 $to['d'] = $now['mday'];
1364 $to['M'] = $now['mon'];
1365 $to['Y'] = $now['year'];
1366 $to['H'] = 23;
1367 $to['i'] = $to['s'] = 59;
1368 break;
6a488035
TO
1369 }
1370 break;
1371
1372 case 'day':
1373 switch ($relativeTerm) {
1374 case 'this':
1375 $from['d'] = $to['d'] = $now['mday'];
1376 $from['M'] = $to['M'] = $now['mon'];
1377 $from['Y'] = $to['Y'] = $now['year'];
1378 break;
1379
1380 case 'previous':
1381 $from['d'] = $now['mday'];
1382 $from['M'] = $now['mon'];
1383 $from['Y'] = $now['year'];
1384 $from = self::intervalAdd('day', -1, $from);
1385 $to['d'] = $from['d'];
1386 $to['M'] = $from['M'];
1387 $to['Y'] = $from['Y'];
1388 break;
1389
1390 case 'previous_before':
1391 $from['d'] = $now['mday'];
1392 $from['M'] = $now['mon'];
1393 $from['Y'] = $now['year'];
1394 $from = self::intervalAdd('day', -2, $from);
1395 $to['d'] = $from['d'];
1396 $to['M'] = $from['M'];
1397 $to['Y'] = $from['Y'];
1398 break;
1399
1400 case 'previous_2':
1401 $from['d'] = $to['d'] = $now['mday'];
1402 $from['M'] = $to['M'] = $now['mon'];
1403 $from['Y'] = $to['Y'] = $now['year'];
1404 $from = self::intervalAdd('day', -2, $from);
1405 $to = self::intervalAdd('day', -1, $to);
1406 break;
1407
1408 case 'earlier':
1409 $to['d'] = $now['mday'];
1410 $to['M'] = $now['mon'];
1411 $to['Y'] = $now['year'];
1412 unset($from);
1413 break;
1414
1415 case 'greater':
1416 $from['d'] = $now['mday'];
1417 $from['M'] = $now['mon'];;
1418 $from['Y'] = $now['year'];
1419 unset($to);
1420 break;
1421 }
1422 break;
1423 }
1424
1425 foreach (array(
1426 'from', 'to') as $item) {
1427 if (!empty($$item)) {
1428 $dateRange[$item] = self::format($$item);
1429 }
1430 else {
1431 $dateRange[$item] = NULL;
1432 }
1433 }
1434 return $dateRange;
1435 }
1436
1437 /**
1438 * Function to calculate current fiscal year based on the fiscal month and day
1439 *
1440 * @param int $fyDate Fiscal start date
1441 *
1442 * @param int $fyMonth Fiscal Start Month
1443 *
1444 * @return int $fy Current Fiscl Year
1445 * @access public
1446 * @static
1447 */
1448 static function calculateFiscalYear($fyDate, $fyMonth) {
1449 $date = date("Y-m-d");
1450 $currentYear = date("Y");
1451
1452 //recalculate the date because month 4::04 make the difference
1453 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1454 $fyDate = $fiscalYear[2];
1455 $fyMonth = $fiscalYear[1];
1456 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1457
1458 if ($fyStartDate > $date) {
1459 $fy = intval(intval($currentYear) - 1);
1460 }
1461 else {
1462 $fy = intval($currentYear);
1463 }
1464 return $fy;
1465 }
1466
1467 /**
1468 * Function to process date, convert to mysql format
1469 *
f4aaa82a
EM
1470 * @param string $date date string
1471 * @param string $time time string
1472 * @param bool|string $returnNullString 'null' needs to be returned
6a488035 1473 * so that db oject will set null in db
f4aaa82a 1474 * @param string $format expected return date format.( default is mysql )
6a488035 1475 *
f4aaa82a 1476 * @return string $mysqlDate date format that is excepted by mysql
6a488035
TO
1477 */
1478 static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1479 $mysqlDate = NULL;
1480
1481 if ($returnNullString) {
1482 $mysqlDate = 'null';
1483 }
1484
1485 if (trim($date)) {
1486 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1487 }
1488
1489 return $mysqlDate;
1490 }
1491
1492 /**
1493 * Function to convert mysql to date plugin format
1494 *
f4aaa82a
EM
1495 * @param string $mysqlDate date string
1496 *
1497 * @param null $formatType
1498 * @param null $format
1499 * @param null $timeFormat
6a488035 1500 *
f4aaa82a 1501 * @return array $date and time
6a488035
TO
1502 */
1503 static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
1504 // if date is not passed assume it as today
1505 if (!$mysqlDate) {
1506 $mysqlDate = date('Y-m-d G:i:s');
1507 }
1508
1509 $config = CRM_Core_Config::singleton();
1510 if ($formatType) {
1511 // get actual format
1512 $params = array('name' => $formatType);
1513 $values = array();
1514 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
1515
1516 if ($values['date_format']) {
1517 $format = $values['date_format'];
1518 }
1519
1520 if (isset($values['time_format'])) {
1521 $timeFormat = $values['time_format'];
1522 }
1523 }
1524
1525 // now we set display date using js, hence we should always setdefault
1526 // 'm/d/Y' format. So that submitted value is alwats mm/dd/YY format
1527 // note that for date display we dynamically create text field
1528 /*
1529 if ( !$format ) {
1530 $format = $config->dateInputFormat;
1531 }
1532
1533 // get actual format
1534 $actualPHPFormats = CRM_Core_SelectValues::datePluginToPHPFormats( );
1535 $dateFormat = CRM_Utils_Array::value( $format, $actualPHPFormats );
1536 */
1537
1538
1539 $dateFormat = 'm/d/Y';
1540 $date = date($dateFormat, strtotime($mysqlDate));
1541
1542 if (!$timeFormat) {
1543 $timeFormat = $config->timeInputFormat;
1544 }
1545
1546 $actualTimeFormat = "g:iA";
1547 $appendZeroLength = 7;
1548 if ($timeFormat > 1) {
1549 $actualTimeFormat = "G:i";
1550 $appendZeroLength = 5;
1551 }
1552
1553 $time = date($actualTimeFormat, strtotime($mysqlDate));
1554
1555 // need to append zero for hours < 10
1556 if (strlen($time) < $appendZeroLength) {
1557 $time = '0' . $time;
1558 }
1559
1560 return array($date, $time);
1561 }
1562
1563 /**
1564 * Function get date format
1565 *
1566 * @param string $formatType Date name e.g. birth
1567 *
1568 * @return string $format
1569 */
1570 static function getDateFormat($formatType = NULL) {
1571 $format = NULL;
1572 if ($formatType) {
395d8dc6 1573 $format = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PreferencesDate',
6a488035
TO
1574 $formatType, 'date_format', 'name'
1575 );
1576 }
1577
1578 if (!$format) {
1579 $config = CRM_Core_Config::singleton();
1580 $format = $config->dateInputFormat;
1581 }
1582 return $format;
1583 }
1584
cf142e47
DL
1585 /**
1586 * Get the time in UTC for the current time. You can optionally send an offset from the current time if needed
1587 *
1588 * @param $offset int the offset from the current time in seconds
1589 *
1590 * @return the time in UTC
1591 * @static
1592 * @public
1593 */
1594 static function getUTCTime($offset = 0) {
6a488035
TO
1595 $originalTimezone = date_default_timezone_get();
1596 date_default_timezone_set('UTC');
1597 $time = time() + $offset;
1598 $now = date('YmdHis', $time);
1599 date_default_timezone_set($originalTimezone);
1600 return $now;
1601 }
1602
1603
5bc392e6
EM
1604 /**
1605 * @param $date
1606 * @param $dateType
1607 *
1608 * @return null|string
1609 */
6a488035
TO
1610 static function formatDate($date, $dateType) {
1611 $formattedDate = NULL;
1612 if (empty($date)) {
1613 return $formattedDate;
1614 }
1615
1616 //1. first convert date to default format.
1617 //2. append time to default formatted date (might be removed during format)
1618 //3. validate date / date time.
1619 //4. If date and time then convert to default date time format.
1620
1621 $dateKey = 'date';
1622 $dateParams = array($dateKey => $date);
1623
1624 if (CRM_Utils_Date::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
1625 $dateVal = $dateParams[$dateKey];
1626 $ruleName = 'date';
1627 if ($dateType == 1) {
1628 $matches = array();
1629 if (preg_match("/(\s(([01]\d)|[2][0-3]):([0-5]\d))$/", $date, $matches)) {
1630 $ruleName = 'dateTime';
1631 if (strpos($date, '-') !== FALSE) {
1632 $dateVal .= array_shift($matches);
1633 }
1634 }
1635 }
1636
1637 // validate date.
0e6e8724 1638 $valid = CRM_Utils_Rule::$ruleName($dateVal);
6a488035
TO
1639
1640 if ($valid) {
1641 //format date and time to default.
1642 if ($ruleName == 'dateTime') {
1643 $dateVal = CRM_Utils_Date::customFormat(preg_replace("/(:|\s)?/", "", $dateVal), '%Y%m%d%H%i');
1644 //hack to add seconds
1645 $dateVal .= '00';
1646 }
1647 $formattedDate = $dateVal;
1648 }
1649 }
1650
1651 return $formattedDate;
1652 }
1653
1654}
1655