Created
May 31, 2017 12:35
-
-
Save calexandrepcjr/752b8a47299d01da2370553d032c88f4 to your computer and use it in GitHub Desktop.
A helper to play with Dates
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
/* | |
$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