Created
July 15, 2021 09:35
-
-
Save finagin/821862cc608dc593fe785aac7e4f98d2 to your computer and use it in GitHub Desktop.
Month boundaries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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