Get months within a range of dates in php [closed]

0

Hello, who helps me get months within a range of example dates

$fechaRegistro="2017-07-21";
$fechaCorte="2017-11-21";

I want to get the months from $fechaRegistro to $fechaCorte

I have programmed the following:

 Function contarMeses($a){
      $f1 = new DateTime( $a[0]);
      $f2 = new DateTime($a[1]);
      $d = $f1->diff($f2);
      $m = ($d->y * 12)+$d->m;
      Return $m;
    }

   function calculaFecha($a) { 
     $modo = ($a[0] == "months")? "months" : $a[0];
     $valor = $a[1];
     $fecha_inicio = strtotime($a[2]);
     $calculo = strtotime("$valor $modo","$fecha-inicio");
     Return date("Y-m-d",$calculo);
   }


  function verMeses($a){
      $f1 = $a[0];
      $f2 = $a[1];
      $countMeses = contarMeses(array($f1,$f2));

     $m = "";
     For($i = 0; $i < $countMeses ; $i++){
          $m .= calculaFecha( array("" , $i+1 , $f1)."<br>";
       }
       Echo $m;
      }

    verMeses(
        array(
            "2017-07-21",
             "2017-11-21"
        )
     );
    
asked by JeanCarlosProgramer 22.07.2017 в 02:08
source

2 answers

0

I think this function is going to help you. (leave it a single)

  function verMeses($a){

   $f1 = new DateTime( $a[0] );
   $f2 = new DateTime( $a[1] );

  // mostrara las fechas
  echo "valor f1 : " . $f1->format('d-m-Y') . "\n";
  echo "valor f2 : " . $f2->format('d-m-Y') . "\n";

  // obtener la diferencia de fechas
  $d = $f1->diff($f2);
  $difmes =  $d->format('%m');

  echo " Cantidad de meses " . $difmes . "\n";

  $impf = $f1;
  for($i = 1; $i <= $difmes; $i++){
      // despliega los meses
      $impf->add(new DateInterval('P1M'));
      echo  $impf->format('d-m-Y') . " - " .$i.  "\n";
  }
}

 verMeses(  array(   "2017-07-21",   "2017-11-22" )    );
    
answered by 22.07.2017 / 05:35
source
0

ok, I edit my answer. Try this:

$f1 = new DateTime('2017-07-21');
    $f2 = new DateTime('2017-11-21');

    $cant_meses = $f2->diff($f1);
    $cant_meses = $cant_meses->format('%m'); //devuelve el numero de meses entre ambas fechas.
    $listaMeses = array($f1->format('Y-m-d'));

    for ($i = 1; $i <= $cant_meses; $i++) {

        $ultimaFecha = end($listaMeses);
        $ultimaFecha = new DateTime($ultimaFecha);
        $nuevaFecha = $ultimaFecha->add(new DateInterval("P1M"));
        $nuevaFecha = $nuevaFecha->format('Y-m-d');

        array_push($listaMeses, $nuevaFecha) ;

    }

debug ($ listMothers); die;

array(
(int) 0 => '2017-07-21',
(int) 1 => '2017-08-21',
(int) 2 => '2017-09-21',
(int) 3 => '2017-10-21',
(int) 4 => '2017-11-21'

)

    
answered by 22.07.2017 в 02:30