/**
* Get a range of datetimes
* Method 1: Get date ranges between $start_at and $end_at
* Method 2: Get a specified number of dates by using $count
* @param null $start_at
* @param null $end_at
* @param string $step
* @param null $count
* @param Y-m-d H:i:s $format_str
* @return array
* @throws \Exception
*/
public static function getDatetimesArray($start_at = null, $end_at = null, $step = '+1 hour', $count = null, $format_str = 'Y-m-d H:i:s')
{
/**
* Format all datetimes
* @param $timestamp
* @return false|string
*/
$format = function($timestamp) use($format_str) {
return date($format_str, $timestamp);
};
if($start_at == null) {
$start_at = $format(time());
}
$datetimes = array();
$datetimes[] = $format(strtotime($start_at));
if($end_at !== null) {
while($start_at < $end_at) {
$datetimes[] = $format(strtotime($step, strtotime($start_at)));
$start_at = $datetimes[count($datetimes) - 1];
}
}
else if($count !== null) {
for($i = 0; $i < $count; $i++) {
$datetimes[] = $format(strtotime($step, strtotime($start_at)));
$start_at = $datetimes[count($datetimes) - 1];
}
}
else {
throw new \Exception('Expecting parameter from $end_at or $count');
}
return $datetimes;
}
Comments