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