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