Skip to content

Instantly share code, notes, and snippets.

@finagin
Created July 15, 2021 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save finagin/821862cc608dc593fe785aac7e4f98d2 to your computer and use it in GitHub Desktop.
Save finagin/821862cc608dc593fe785aac7e4f98d2 to your computer and use it in GitHub Desktop.
Month boundaries
<?php
/**
* @param \DateTime|null $date Дата для которой рассчитать начало и конец месяца.
* Если не передать считает от текущего момента.
*
* @return array<string, int> Массив из трёх timestamp: начало месяца, конец месяца, дата от которой производился расчёт
* @throws \Exception
*/
function boundaries(\DateTime $date = null)
{
function wrap($object) {return $object;} // for PHP <= 7.0
if ($date === null) {
$date = new \DateTime();
}
$date_start = new \DateTime($date->format('Y-m-1'));
$date_end = wrap(clone $date_start)->modify('+1 month -1 second');
$arr = array(
'date_start' => $date_start,
'date_end' => $date_end,
'date' => $date
);
foreach ($arr as $key => $value) {
$result[] = $value->getTimestamp();
$result[$key] = $value->getTimestamp();
}
return $result;
}
var_dump(boundaries());
// PHP >= 7.2
[$date_start, $date_end, $date] = boundaries();
// PHP >= 5.3
$dates = boundaries();
$dates['date_start'];
$dates['date_end'];
$dates['date'];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment