Home > other >  Get date difference from looped dates in php
Get date difference from looped dates in php

Time:01-16

Can I have your help on this problem. I want the diff of date like: Jan-Feb = 31, Feb-Mar = 28|29, and so on.

$n_months = 12;
for ($i=0; $i < $n_months; $i  ) { 
 $day = $dt->format('j');
 $dt->modify('first day of  1 month');
 $dt->modify(' ' . (min($day, $dt->format('t')) - 1) . ' days');
 $date1 = $dt->format('Y-m-d');

 $s = new DateTime($date1);
 $e = new DateTime($end);
 $interval = $s->diff($e);
  
   echo $interval->format('%d days');
 $end = $date1;
}

CodePudding user response:

you can try get days in month like this

<?php
$n_months = 14;
$date  = new DateTime("2022-01-01");
for ($i = 1; $i <= $n_months; $i  ) {
    $thisM = $date->format("M");
    $thisY = $date->format("Y");
    $days  = $date->format("t");
    $date->modify(" 1 month");
    $nextM = $date->format("M");
    $nextY = $date->format("Y");
    echo "{$thisM} {$thisY} - {$nextM} {$nextY} = {$days}\n";
}
?>

CodePudding user response:

Here it is (;

<?php  
$n_months = 14; 
$start_date = strtotime(date('Y-m-d')); // or strtotime('2022-01-01')

while(@$count<$n_months){
 
    $date = (!@$count ? date('Y-m',$start_date) : date('Y-m',strtotime(' '.$count.' month', $start_date)));
    @$count =1;
    list($y,$m) = explode('-',$date);
    $days=cal_days_in_month(CAL_GREGORIAN,$m,$y);

    $m_from = date("M", mktime(0, 0, 0, $m, 10)); $m =1;
    $m_to = date("M", mktime(0, 0, 0, ($m>12 ? 1 : $m), 10));

    echo $m_from.'-'.$m_to.'='.$days.'<br/>';
}
?>

Jan-Feb=31
to Feb-Mar=29

  • Related