benshepherd

getDatetimesArray

Jun 25th, 2018
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.56 KB | None | 0 0
  1.     /**
  2.      * Get a range of datetimes
  3.      * Method 1: Get date ranges between $start_at and $end_at
  4.      * Method 2: Get a specified number of dates by using $count
  5.      * @param null $start_at
  6.      * @param null $end_at
  7.      * @param string $step
  8.      * @param null $count
  9.      * @param Y-m-d H:i:s $format_str
  10.      * @return array
  11.      * @throws \Exception
  12.      */
  13.     public static function getDatetimesArray($start_at = null, $end_at = null, $step = '+1 hour', $count = null, $format_str = 'Y-m-d H:i:s')
  14.     {
  15.         /**
  16.          * Format all datetimes
  17.          * @param $timestamp
  18.          * @return false|string
  19.          */
  20.         $format = function($timestamp) use($format_str) {
  21.             return date($format_str, $timestamp);
  22.         };
  23.  
  24.         if($start_at == null) {
  25.             $start_at = $format(time());
  26.         }
  27.  
  28.         $datetimes = array();
  29.         $datetimes[] = $format(strtotime($start_at));
  30.  
  31.         if($end_at !== null) {
  32.             while($start_at < $end_at) {
  33.                 $datetimes[] = $format(strtotime($step, strtotime($start_at)));
  34.                 $start_at = $datetimes[count($datetimes) - 1];
  35.             }
  36.         }
  37.         else if($count !== null) {
  38.             for($i = 0; $i < $count; $i++) {
  39.                 $datetimes[] = $format(strtotime($step, strtotime($start_at)));
  40.                 $start_at = $datetimes[count($datetimes) - 1];
  41.             }
  42.         }
  43.         else {
  44.             throw new \Exception('Expecting parameter from $end_at or $count');
  45.         }
  46.  
  47.         return $datetimes;
  48.     }
Advertisement
Add Comment
Please, Sign In to add comment