Get the number of days between two dates just for the current month

141 Views Asked by At

I have to calculate the number of days that have passed between two dates, but I need to split the days difference per month and just display the current month passed days. This is needed to calculate vacations time for an employee.

Note: I need to make this on PHP 5.4. For example I'm going to use this two dates and a current month:

<?php
CurrentMonth="04";
FirstDate="2021-03-28";
SecondDate="2021-04-15";
?>

So, for this example the total day diff is 18 days, but I just need to return the 15 days passed in the current month "04".

Any suggestions? Thanks in advance.

2

There are 2 best solutions below

2
Pablo LaVegui On

A simple solution for a simple problem:

$firstDate = new DateTime('2021-03-28');
$secondDate = new DateTime('2021-04-15');

$diff = $firstDate->format('n') < $secondDate->format('n')
    ? $secondDate->format('j')
    : $secondDate->format('j') - $firstDate->format('j');

Using the current month as variable:

$currentMonth = '04';
$firstDate = new DateTime('2021-03-28');
$secondDate = new DateTime('2021-04-15');

$firstDateMonth = $firstDate->format('m');
$secondDateMonth = $secondDate->format('m');

if ($currentMonth === $firstDateMonth && $currentMonth === $secondDateMonth) {
    $diff = $secondDate->format('j') - $firstDate->format('j');
} else {
    $diff = $currentMonth === $secondDateMonth
        ? $secondDate->format('j')
        : null;
}
0
Rafael Granados On

Just made a little modification to Pablo's code for take the days diff if the current month is in the first date:

<?php
$currentMonth = '04';
$firstDate = new DateTime('2021-03-28');
$lastDay= new DateTime($firstDate->format( 'Y-m-t' )); //last day of $firstDate month
$secondDate = new DateTime('2021-04-15');
$firstDay= $secondDate->format( 'Y-m-01' ); //first day of $secondDate month
$firstDayDT = new DateTime($firstDay); //datetime for $firstDay

$firstDateMonth = $firstDate->format('m');
$secondDateMonth = $secondDate->format('m');

if ($currentMonth === $secondDateMonth) {
    $diff = $secondDate->format('j') - $firstDayDT->format('j')+1; //sum +1 day
} else if ($currentMonth === $firstDateMonth) {
    $diff = $lastDay->format('j') - $firstDate->format('j');
};
echo $diff;

If current month is "03", the code returns 3, if the month is "04", returns 15.