Merge pull request #5292 from jitendrapurohit/CRM-15933
[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
51 * formatted string for date
52 *
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
172 * 0-based array with abbreviated weekday names
173 *
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
193 * 0-based array with full weekday names
194 *
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
216 * 1-based array with abbreviated month names
217 *
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
239 * 1-based array with full month names
240 *
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
301 * the $format-formatted $date
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
435 * date/datetime in ISO format
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
478 * date/datetime in MySQL format
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 */
497 public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
498 $now = getdate();
499 $cen = substr($now['year'], 0, 2);
500 $prevCen = $cen - 1;
501
502 $value = NULL;
503 if (!empty($params[$dateParam])) {
504 // suppress hh:mm or hh:mm:ss if it exists CRM-7957
505 $value = preg_replace("/(\s(([01]\d)|[2][0-3])(:([0-5]\d)){1,2})$/", "", $params[$dateParam]);
506 }
507
508 switch ($dateType) {
509 case 1:
510 if (!preg_match('/^\d\d\d\d-?(\d|\d\d)-?(\d|\d\d)$/', $value)) {
511 return FALSE;
512 }
513 break;
514
515 case 2:
516 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d$/', $value)) {
517 return FALSE;
518 }
519 break;
520
521 case 4:
522 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d$/', $value)) {
523 return FALSE;
524 }
525 break;
526
527 case 8:
528 if (!preg_match('/^[A-Za-z]*.[ \t]?\d\d\,[ \t]?\d\d\d\d$/', $value)) {
529 return FALSE;
530 }
531 break;
532
533 case 16:
534 if (!preg_match('/^\d\d-[A-Za-z]{3}.*-\d\d$/', $value) && !preg_match('/^\d\d[-\/]\d\d[-\/]\d\d$/', $value)) {
535 return FALSE;
536 }
537 break;
538
539 case 32:
540 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d/', $value)) {
541 return FALSE;
542 }
543 break;
544 }
545
546 if ($dateType == 1) {
547 $formattedDate = explode("-", $value);
548 if (count($formattedDate) == 3) {
549 $year = (int) $formattedDate[0];
550 $month = (int) $formattedDate[1];
551 $day = (int) $formattedDate[2];
552 }
553 elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
554 return TRUE;
555 }
556 else {
557 return FALSE;
558 }
559 }
560
561 if ($dateType == 2 || $dateType == 4) {
562 $formattedDate = explode("/", $value);
563 if (count($formattedDate) != 3) {
564 $formattedDate = explode("-", $value);
565 }
566 if (count($formattedDate) == 3) {
567 $year = (int) $formattedDate[2];
568 $month = (int) $formattedDate[0];
569 $day = (int) $formattedDate[1];
570 }
571 else {
572 return FALSE;
573 }
574 }
575 if ($dateType == 8) {
576 $dateArray = explode(' ', $value);
577 // ignore comma(,)
578 $dateArray[1] = (int) substr($dateArray[1], 0, 2);
579
580 $monthInt = 0;
581 $fullMonths = self::getFullMonthNames();
582 foreach ($fullMonths as $key => $val) {
583 if (strtolower($dateArray[0]) == strtolower($val)) {
584 $monthInt = $key;
585 break;
586 }
587 }
588 if (!$monthInt) {
589 $abbrMonths = self::getAbbrMonthNames();
590 foreach ($abbrMonths as $key => $val) {
591 if (strtolower(trim($dateArray[0], ".")) == strtolower($val)) {
592 $monthInt = $key;
593 break;
594 }
595 }
596 }
597 $year = (int) $dateArray[2];
598 $day = (int) $dateArray[1];
599 $month = (int) $monthInt;
600 }
601 if ($dateType == 16) {
602 $dateArray = explode('-', $value);
603 if (count($dateArray) != 3) {
604 $dateArray = explode('/', $value);
605 }
606
607 if (count($dateArray) == 3) {
608 $monthInt = 0;
609 $fullMonths = self::getFullMonthNames();
610 foreach ($fullMonths as $key => $val) {
611 if (strtolower($dateArray[1]) == strtolower($val)) {
612 $monthInt = $key;
613 break;
614 }
615 }
616 if (!$monthInt) {
617 $abbrMonths = self::getAbbrMonthNames();
618 foreach ($abbrMonths as $key => $val) {
619 if (strtolower(trim($dateArray[1], ".")) == strtolower($val)) {
620 $monthInt = $key;
621 break;
622 }
623 }
624 }
625 if (!$monthInt) {
626 $monthInt = $dateArray[1];
627 }
628
629 $year = (int) $dateArray[2];
630 $day = (int) $dateArray[0];
631 $month = (int) $monthInt;
632 }
633 else {
634 return FALSE;
635 }
636 }
637 if ($dateType == 32) {
638 $formattedDate = explode("/", $value);
639 if (count($formattedDate) == 3) {
640 $year = (int) $formattedDate[2];
641 $month = (int) $formattedDate[1];
642 $day = (int) $formattedDate[0];
643 }
644 else {
645 return FALSE;
646 }
647 }
648
649 $month = ($month < 10) ? "0" . "$month" : $month;
650 $day = ($day < 10) ? "0" . "$day" : $day;
651
652 $year = (int ) $year;
653 // simple heuristic to determine what century to use
654 // 00 - 20 is always 2000 - 2020
655 // 21 - 99 is always 1921 - 1999
656 if ($year < 21) {
657 $year = (strlen($year) == 1) ? $cen . '0' . $year : $cen . $year;
658 }
659 elseif ($year < 100) {
660 $year = $prevCen . $year;
661 }
662
663 if ($params[$dateParam]) {
664 $params[$dateParam] = "$year$month$day";
665 }
666 //if month is invalid return as error
667 if ($month !== '00' && $month <= 12) {
668 return TRUE;
669 }
670 return FALSE;
671 }
672
673 /**
674 * @param $date
675 *
676 * @return bool
677 */
678 public static function isDate(&$date) {
679 if (CRM_Utils_System::isNull($date)) {
680 return FALSE;
681 }
682 return TRUE;
683 }
684
685 /**
686 * @param null $timeStamp
687 *
688 * @return bool|string
689 */
690 public static function currentDBDate($timeStamp = NULL) {
691 return $timeStamp ? date('YmdHis', $timeStamp) : date('YmdHis');
692 }
693
694 /**
695 * @param $date
696 * @param null $now
697 *
698 * @return bool
699 */
700 public static function overdue($date, $now = NULL) {
701 $mysqlDate = self::isoToMysql($date);
702 if (!$now) {
703 $now = self::currentDBDate();
704 }
705 else {
706 $now = self::isoToMysql($now);
707 }
708
709 return ($mysqlDate >= $now) ? FALSE : TRUE;
710 }
711
712 /**
713 * Get customized today.
714 *
715 * This function is used for getting customized today. To get
716 * actuall today pass 'dayParams' as null. or else pass the day,
717 * month, year values as array values
718 * Example: $dayParams = array(
719 * 'day' => '25', 'month' => '10',
720 * 'year' => '2007' );
721 *
722 * @param array $dayParams of the day, month, year.
723 * Array of the day, month, year.
724 * values.
725 * @param string $format
726 * Expected date format( default.
727 * format is 2007-12-21 )
728 *
729 * @return string
730 * Return the customized todays date (Y-m-d)
731 */
732 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
733 if (is_null($dayParams) || empty($dayParams)) {
734 $today = date($format);
735 }
736 else {
737 $today = date($format, mktime(0, 0, 0,
738 $dayParams['month'],
739 $dayParams['day'],
740 $dayParams['year']
741 ));
742 }
743
744 return $today;
745 }
746
747 /**
748 * Find whether today's date lies in
749 * the given range
750 *
751 * @param date $startDate
752 * Start date for the range.
753 * @param date $endDate
754 * End date for the range.
755 *
756 * @return bool
757 * true if today's date is in the given date range
758 */
759 public static function getRange($startDate, $endDate) {
760 $today = date("Y-m-d");
761 $mysqlStartDate = self::isoToMysql($startDate);
762 $mysqlEndDate = self::isoToMysql($endDate);
763 $mysqlToday = self::isoToMysql($today);
764
765 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
766 return TRUE;
767 }
768 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
769 return TRUE;
770 }
771 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
772 return TRUE;
773 }
774 return FALSE;
775 }
776
777 /**
778 * Get start date and end from
779 * the given relative term and unit
780 *
781 * @param date $relative
782 * Eg: term.unit.
783 *
784 * @param $from
785 * @param $to
786 *
787 * @return array
788 * start date, end date
789 */
790 public static function getFromTo($relative, $from, $to) {
791 if ($relative) {
792 list($term, $unit) = explode('.', $relative);
793 $dateRange = self::relativeToAbsolute($term, $unit);
794 $from = $dateRange['from'];
795 //Take only Date Part, Sometime Time part is also present in 'to'
796 $to = substr($dateRange['to'], 0, 8);
797 }
798
799 $from = self::processDate($from);
800 $to = self::processDate($to, '235959');
801
802 return array($from, $to);
803 }
804
805 /**
806 * Calculate Age in Years if greater than one year else in months.
807 *
808 * @param date $birthDate
809 * Birth Date.
810 *
811 * @return int
812 * array $results contains years or months
813 */
814 static public function calculateAge($birthDate) {
815 $results = array();
816 $formatedBirthDate = CRM_Utils_Date::customFormat($birthDate, '%Y-%m-%d');
817
818 $bDate = explode('-', $formatedBirthDate);
819 $birthYear = $bDate[0];
820 $birthMonth = $bDate[1];
821 $birthDay = $bDate[2];
822 $year_diff = date("Y") - $birthYear;
823
824 // don't calculate age CRM-3143
825 if ($birthYear == '1902') {
826 return $results;
827 }
828
829 switch ($year_diff) {
830 case 1:
831 $month = (12 - $birthMonth) + date("m");
832 if ($month < 12) {
833 if (date("d") < $birthDay) {
834 $month--;
835 }
836 $results['months'] = $month;
837 }
838 elseif ($month == 12 && (date("d") < $birthDay)) {
839 $results['months'] = $month - 1;
840 }
841 else {
842 $results['years'] = $year_diff;
843 }
844 break;
845
846 case 0:
847 $month = date("m") - $birthMonth;
848 $results['months'] = $month;
849 break;
850
851 default:
852 $results['years'] = $year_diff;
853 if ((date("m") < $birthMonth) || (date("m") == $birthMonth) && (date("d") < $birthDay)) {
854 $results['years']--;
855 }
856 }
857
858 return $results;
859 }
860
861 /**
862 * Calculate next payment date according to provided unit & interval
863 *
864 * @param string $unit
865 * Frequency unit like year,month, week etc.
866 *
867 * @param int $interval
868 * Frequency interval.
869 *
870 * @param array $date
871 * Start date of pledge.
872 *
873 * @param bool $dontCareTime
874 *
875 * @return array
876 * 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
969 * start date and end date for the relative time frame
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',
1621 'to',
1622 ) as $item) {
1623 if (!empty($$item)) {
1624 $dateRange[$item] = self::format($$item);
1625 }
1626 else {
1627 $dateRange[$item] = NULL;
1628 }
1629 }
1630 return $dateRange;
1631 }
1632
1633 /**
1634 * Calculate current fiscal year based on the fiscal month and day.
1635 *
1636 * @param int $fyDate
1637 * Fiscal start date.
1638 *
1639 * @param int $fyMonth
1640 * Fiscal Start Month.
1641 *
1642 * @return int
1643 * $fy Current Fiscl Year
1644 */
1645 public static function calculateFiscalYear($fyDate, $fyMonth) {
1646 $date = date("Y-m-d");
1647 $currentYear = date("Y");
1648
1649 //recalculate the date because month 4::04 make the difference
1650 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1651 $fyDate = $fiscalYear[2];
1652 $fyMonth = $fiscalYear[1];
1653 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1654
1655 if ($fyStartDate > $date) {
1656 $fy = intval(intval($currentYear) - 1);
1657 }
1658 else {
1659 $fy = intval($currentYear);
1660 }
1661 return $fy;
1662 }
1663
1664 /**
1665 * Function to process date, convert to mysql format
1666 *
1667 * @param string $date
1668 * Date string.
1669 * @param string $time
1670 * Time string.
1671 * @param bool|string $returnNullString 'null' needs to be returned
1672 * so that db oject will set null in db
1673 * @param string $format
1674 * Expected return date format.( default is mysql ).
1675 *
1676 * @return string
1677 * date format that is excepted by mysql
1678 */
1679 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1680 $mysqlDate = NULL;
1681
1682 if ($returnNullString) {
1683 $mysqlDate = 'null';
1684 }
1685
1686 if (trim($date)) {
1687 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1688 }
1689
1690 return $mysqlDate;
1691 }
1692
1693 /**
1694 * Function to convert mysql to date plugin format.
1695 *
1696 * @param string $mysqlDate
1697 * Date string.
1698 *
1699 * @param null $formatType
1700 * @param null $format
1701 * @param null $timeFormat
1702 *
1703 * @return array
1704 * and time
1705 */
1706 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
1707 // if date is not passed assume it as today
1708 if (!$mysqlDate) {
1709 $mysqlDate = date('Y-m-d G:i:s');
1710 }
1711
1712 $config = CRM_Core_Config::singleton();
1713 if ($formatType) {
1714 // get actual format
1715 $params = array('name' => $formatType);
1716 $values = array();
1717 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
1718
1719 if ($values['date_format']) {
1720 $format = $values['date_format'];
1721 }
1722
1723 if (isset($values['time_format'])) {
1724 $timeFormat = $values['time_format'];
1725 }
1726 }
1727
1728 // now we set display date using js, hence we should always setdefault
1729 // 'm/d/Y' format. So that submitted value is alwats mm/dd/YY format
1730 // note that for date display we dynamically create text field
1731 /*
1732 if ( !$format ) {
1733 $format = $config->dateInputFormat;
1734 }
1735
1736 // get actual format
1737 $actualPHPFormats = CRM_Core_SelectValues::datePluginToPHPFormats( );
1738 $dateFormat = CRM_Utils_Array::value( $format, $actualPHPFormats );
1739 */
1740
1741 $dateFormat = 'm/d/Y';
1742 $date = date($dateFormat, strtotime($mysqlDate));
1743
1744 if (!$timeFormat) {
1745 $timeFormat = $config->timeInputFormat;
1746 }
1747
1748 $actualTimeFormat = "g:iA";
1749 $appendZeroLength = 7;
1750 if ($timeFormat > 1) {
1751 $actualTimeFormat = "G:i";
1752 $appendZeroLength = 5;
1753 }
1754
1755 $time = date($actualTimeFormat, strtotime($mysqlDate));
1756
1757 // need to append zero for hours < 10
1758 if (strlen($time) < $appendZeroLength) {
1759 $time = '0' . $time;
1760 }
1761
1762 return array($date, $time);
1763 }
1764
1765 /**
1766 * Function get date format.
1767 *
1768 * @param string $formatType
1769 * Date name e.g. birth.
1770 *
1771 * @return string
1772 */
1773 public static function getDateFormat($formatType = NULL) {
1774 $format = NULL;
1775 if ($formatType) {
1776 $format = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PreferencesDate',
1777 $formatType, 'date_format', 'name'
1778 );
1779 }
1780
1781 if (!$format) {
1782 $config = CRM_Core_Config::singleton();
1783 $format = $config->dateInputFormat;
1784 }
1785 return $format;
1786 }
1787
1788 /**
1789 * Get the time in UTC for the current time. You can optionally send an offset from the current time if needed
1790 *
1791 * @param int $offset
1792 * the offset from the current time in seconds.
1793 *
1794 * @return string
1795 * the time in UTC
1796 */
1797 public static function getUTCTime($offset = 0) {
1798 $originalTimezone = date_default_timezone_get();
1799 date_default_timezone_set('UTC');
1800 $time = time() + $offset;
1801 $now = date('YmdHis', $time);
1802 date_default_timezone_set($originalTimezone);
1803 return $now;
1804 }
1805
1806
1807 /**
1808 * @param $date
1809 * @param $dateType
1810 *
1811 * @return null|string
1812 */
1813 public static function formatDate($date, $dateType) {
1814 $formattedDate = NULL;
1815 if (empty($date)) {
1816 return $formattedDate;
1817 }
1818
1819 //1. first convert date to default format.
1820 //2. append time to default formatted date (might be removed during format)
1821 //3. validate date / date time.
1822 //4. If date and time then convert to default date time format.
1823
1824 $dateKey = 'date';
1825 $dateParams = array($dateKey => $date);
1826
1827 if (CRM_Utils_Date::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
1828 $dateVal = $dateParams[$dateKey];
1829 $ruleName = 'date';
1830 if ($dateType == 1) {
1831 $matches = array();
1832 if (preg_match("/(\s(([01]\d)|[2][0-3]):([0-5]\d))$/", $date, $matches)) {
1833 $ruleName = 'dateTime';
1834 if (strpos($date, '-') !== FALSE) {
1835 $dateVal .= array_shift($matches);
1836 }
1837 }
1838 }
1839
1840 // validate date.
1841 $valid = CRM_Utils_Rule::$ruleName($dateVal);
1842
1843 if ($valid) {
1844 //format date and time to default.
1845 if ($ruleName == 'dateTime') {
1846 $dateVal = CRM_Utils_Date::customFormat(preg_replace("/(:|\s)?/", "", $dateVal), '%Y%m%d%H%i');
1847 //hack to add seconds
1848 $dateVal .= '00';
1849 }
1850 $formattedDate = $dateVal;
1851 }
1852 }
1853
1854 return $formattedDate;
1855 }
1856
1857 }