Skip to content

Instantly share code, notes, and snippets.

@calexandrepcjr
Created May 31, 2017 12:35
Show Gist options
  • Save calexandrepcjr/752b8a47299d01da2370553d032c88f4 to your computer and use it in GitHub Desktop.
Save calexandrepcjr/752b8a47299d01da2370553d032c88f4 to your computer and use it in GitHub Desktop.
A helper to play with Dates
/*
$dateStart = "2016/12/14";
$dateFin = "2017/04/21"
[2016/12/14 - 2016/12/31] => 17 days
[2017/01/01 - 2017/01/31] => 31 days
[2017/02/01 - 2017/02/28] => 28 days
[2017/03/01 - 2017/03/30] => 31 days
[2017/04/01 - 2017/04/21] => 21 days
*/
<?php
function how_many_days($firstDate, $lastDate)
{
$dateStart = new DateTime($firstDate);
$dateFin = new DateTime($lastDate);
$totalMonths = $dateStart->diff($dateFin)->m + ($dateStart->diff($dateFin)->y*12);
$result = [];
for ($i = 0; $i <= $totalMonths; $i++)
{
if ($i != 0){
$obj = $dateStart->modify('first day of next month');
}
$firstDay = $dateStart->format('Y/m/d');
if ($i == $totalMonths){
$lastDay = $dateFin->format('Y/m/d');
} else {
$lastDay = $dateStart->format('Y/m/t');
}
$firstDayObj = strtotime($firstDay);
$lastDayObj = strtotime($lastDay);
$totalDays = (int) ceil(($lastDayObj - $firstDayObj) / 86400);
$totalDays = ((int) $dateStart->format('d') == 1) ? $totalDays + 1 : $totalDays;
$result["$firstDay - $lastDay"] = $totalDays;
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment