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