vendor/sentia/utils/DateTimeUtil.php line 15

Open in your IDE?
  1. <?php
  2. namespace Sentia\Utils;
  3. use DateTime;
  4. use Exception;
  5. class DateTimeUtil {
  6.     /**
  7.      * porovnava datumy - pouziva objekty DateTime, ale berie do uvahy len 'd m Y'
  8.      * -1 .. $date1 < $date2
  9.      *  0 .. $date1 = $date2
  10.      *  1 .. $date1 < $date2
  11.      */
  12.     public function compareDates(DateTime $date1 = null, DateTime $date2 = null): int {
  13.         $s1 = $date1 != null ? $date1->format('Y-m-d') : '';
  14.         $s2 = $date2 != null ? $date2->format('Y-m-d') : '';
  15.         return ($s1 < $s2) ? -1 : ($s1 == $s2 ? 0 : 1);
  16.     }
  17.     /**
  18.      * porovnava datumy - berie do uvahy aj hodiny, minuty, sekundy
  19.      * -1 .. $date1 < $date2
  20.      *  0 .. $date1 = $date2
  21.      *  1 .. $date1 < $date2
  22.      */
  23.     public function compareDateTimes(DateTime $dateTime1 = null, DateTime $dateTime2 = null): int {
  24.         $s1 = $dateTime1 !== null ? $dateTime1->format('Y-m-d H:i:s') : '';
  25.         $s2 = $dateTime2 !== null ? $dateTime2->format('Y-m-d H:i:s') : '';
  26.         return ($s1 < $s2) ? -1 : ($s1 == $s2 ? 0 : 1);
  27.     }
  28.     /**
  29.      * vracia vek podla datumu narodenia k dnesnemu dnu, alebo k nejaku inemu dnu
  30.      * @param DateTime $birthDate
  31.      * @param DateTime|null $toDate - datum, ku ktoremu pocitat vek
  32.      */
  33.     public function getAge(DateTime $birthDate = null, DateTime $toDate = null): ?int {
  34.         $ret = null;
  35.         if(null !== $birthDate){
  36.             if($toDate === null){
  37.                 $toDate = new DateTime();
  38.             }
  39.             $ret = floor(($toDate->format("Ymd") - $birthDate->format("Ymd")) / 10000);
  40.         }
  41.         return $ret;
  42.     }
  43.     /**
  44.      * skonvertuje string na DateTime, alebo null, ak nie je alebo je zle zadany.
  45.      * Value moze byt napr. '1.1.2001', '01.01.2001', '31.12.2001', ' 31. 12 . 2001'
  46.      */
  47.     public function stringToDateTime($theValue): ?DateTime {
  48.         if (strlen($theValue) < 8){ // minimum je 8 znakov - '1.1.2001'
  49.             return null;
  50.         }
  51.         // oddelovac je '.'
  52.         $ss = explode('.', $theValue);
  53.         if (count($ss) != 3){
  54.             return null;
  55.         }
  56.         $d = trim($ss[0]);
  57.         $m = trim($ss[1]);
  58.         $y = trim($ss[2]);
  59.         if (!(is_numeric($d) && is_numeric($m) && is_numeric($y))){
  60.             return null;
  61.         }
  62.         $d = (int)$d;
  63.         $m = (int)$m;
  64.         $y = (int)$y;
  65.         if (!($d>=1 && $d<=31 && $m>=1 && $m<=12 && $y>=1900 && $y<=2200)){
  66.             return null;
  67.         }
  68.         try{
  69.             $d = new DateTime($y . '-' . ($m <= 9 ? '0' : '') . $m . '-' . ($d <= 9 ? '0' : '') . $d);
  70.         }catch(Exception $e){
  71.         }
  72.         return $d;
  73.     }
  74.     /**
  75.      * similar to DateTime.modify(), but this method modify result:
  76.      * - if (31.08. +1 month) = 01.10. - from method modify(), but from this method will be result: 30.09.
  77.      * - if (31.05. -1 month) = 01.05. - from method modify(), but from this method will be result: 30.04.
  78.      * @param DateTime $theDateTime - this datetime will be modified
  79.      * @param $thePeriod ('+1 month', '-1 week', '+2 year', ...)
  80.      * @throws Exception
  81.      */
  82.     public function modifyAndAdaptMonth(DateTime $theDateTime, $thePeriod){
  83.         // modify
  84.         $date1 = clone($theDateTime);
  85.         $theDateTime->modify($thePeriod);
  86.         // zisti, ci ide o Year/Month
  87.         $ss = explode(' ', $thePeriod);
  88.         if (count($ss)!=2){
  89.             throw new Exception('Perioda=\''.$thePeriod.'\' je v nespravnom formate!');
  90.         }
  91.         $s = strtolower($ss[1]);
  92.         $isModified = false;
  93.         if ($s=='month' || $s=='year' || $s=='week'){
  94.             // check problematic days
  95.             $d1 = (int)$date1->format('d');
  96.             $d2 = (int)$theDateTime->format('d');
  97.             if ($d1 != $d2){
  98.                 // pri pripocitavani moze nastat napr. 31.08. + 1month = 01.10., ale pre nas je spravna hodnota 30.09.
  99.                 // pri odpocitavani moze nastat napr. 31.05. - 1month = 01.05., ale pre nas je spravna hodnota 30.04.
  100.                 // cize v oboch pripadoch je potrebne odpocitat 1 den (alebo 2, alebo 3)
  101.                 $isModified = true;
  102.                 do{
  103.                     if (!($d1>=29 && $d1<=31 && $d2>=1 && $d2<=3)){
  104.                         throw new Exception('Nepodarilo sa DateTime("'.$theDateTime->format('d.m.Y').'").modify("'.$thePeriod.'")!');
  105.                     }
  106.                     $date1->modify('-1 day');
  107.                     $theDateTime->modify('-1 day');
  108.                     $d1 = (int)$date1->format('d');
  109.                     $d2 = (int)$theDateTime->format('d');
  110.                 }while($d1!=$d2);
  111.             }
  112.         }
  113.         if(isset($thePeriod[0]) && $thePeriod[0] == '+' && !$isModified){
  114.             //echo 'ccc';
  115.             $theDateTime->modify("-1 day");
  116.         }
  117.     }
  118.     /**
  119.      * vracia (true), ak je retazec platnym datumom (napr.: 14.5.2017), vracia (false) ak retazec nie je platny datum.
  120.      */
  121.     public function isDate(string $text): bool {
  122.         $pieces = explode(".", $text);
  123.         $den = isset($pieces[0]) ? $pieces[0] : "";
  124.         $mesiac = isset($pieces[1]) ? $pieces[1] : "";
  125.         $rok = isset($pieces[2]) ? $pieces[2] : "";
  126.         return ((int)$den >= 1 && (int)$den <= 31 && (int)$mesiac >= 1 && (int)$mesiac <= 12 && (int)$rok >= 1901 && (int)$rok <= 3000);
  127.     }
  128.     /**
  129.      * vracia rozdiel medzi dvoma datumami v dnoch
  130.      */
  131.     public function differenceDays(DateTime $datetime1, DateTime $datetime2): int {
  132.         $interval = $datetime1->diff($datetime2);
  133.         return (int)$interval->format('%a');
  134.     }
  135.     /**
  136.      * creates new DateTime object modified by modifyString and timePart
  137.      */
  138.     public function newDateTimeFromNow(string $modifyString, ?string $timePart = null):DateTime{
  139.         $dateTime = new DateTime();
  140.         $dateTime->modify($modifyString);
  141.         if($timePart !== null){
  142.             $timeParts = explode(':', $timePart);
  143.             $hours = isset($timeParts[0]) ? $timeParts[0] : 0;
  144.             $minutes = isset($timeParts[1]) ? $timeParts[1] : 0;
  145.             $seconds = isset($timeParts[2]) ? $timeParts[2] : 0;
  146.             $dateTime->setTime($hours, $minutes, $seconds);
  147.         }
  148.         return $dateTime;
  149.     }
  150.     public function getHoursForForm(): array {
  151.         $ret = [];
  152.         for($i=0; $i<=23; $i++){
  153.             $h = str_pad($i, 2, "0", STR_PAD_LEFT);
  154.             $ret[$h] = $h;
  155.         }
  156.         return $ret;
  157.     }
  158.     public function getMinutesForForm(): array {
  159.         $ret = [];
  160.         for($i=0; $i<=59; $i++){
  161.             $m = str_pad($i, 2, "0", STR_PAD_LEFT);
  162.             $ret[$m] = $m;
  163.         }
  164.         return $ret;
  165.     }
  166.     /**
  167.      * vracia pole rokov medzi datumami
  168.      */
  169.     public function getYearsFromInterval(DateTime $dateFrom, DateTime $dateTill): array {
  170.         if($dateFrom->format("Y") === $dateTill->format("Y")){
  171.             return [(int)$dateFrom->format("Y")];
  172.         }
  173.         $ret = [];
  174.         $yearFrom = (int)$dateFrom->format("Y") < (int)$dateTill->format("Y") ? (int)$dateFrom->format("Y") : (int)$dateTill->format("Y");
  175.         $yearTill = (int)$dateFrom->format("Y") > (int)$dateTill->format("Y") ? (int)$dateFrom->format("Y") : (int)$dateTill->format("Y");
  176.         for($i=$yearFrom; $i<=$yearTill; $i++){
  177.             $ret[] = $i;
  178.         }
  179.         return $ret;
  180.     }
  181.     /**
  182.      * vracia DateTime vhodny na ukoncenie zmluvy.
  183.      * Ak je na vstupe dnesny datum, tak sa vrati aj aktualna casova zlozka
  184.      * Ak je na vstupe iny ako dnesny datum, tak casova zlozka bude 00:00:00
  185.      */
  186.     public function getForInsuranceStart(DateTime $dateTime): DateTime{
  187.         if($dateTime->format("Y-m-d") === date("Y-m-d")){
  188.             return new DateTime();
  189.         }else{
  190.             return new DateTime($dateTime->format("Y-m-d").'00:00:00');
  191.         }
  192.     }
  193. }