Increase a date month by month PHP

1

I have the following variables

$fehchaI ='2016-01-01'; 
$fehchaF ='2017-01-31';

What I want to do is increase the dates month by month and the result is

2016-01-01
2016-01-31
2016-02-01
2016-02-28
2016-03-01
2016-03-31

or

    2016-01-01
    2016-02-01
    2016-03-01
    2016-04-01

and so on until the last one is '2017-01-31'

or some function like MySQL:

SELECT DATE_ADD("2016-01-01", INTERVAL  1 MONTH); 

but for php

Someone who can help me do it in PHP

    
asked by Soldier 20.09.2017 в 19:37
source

2 answers

2

To show the last day of the month:

$dt = new DateTime( '2017-02-01' ); 
echo $dt->format( 't-m-Y' );
// Resultado: 28-02-2017

To show the first day of the following month:

$dt = new DateTime( '2017-01-15' );
$dt->modify( 'first day of next month' );
echo $dt->format( 'd-m-Y' );
// Resultado: 01-02-2017

To show the next month with respect to the given date:

$dt = new DateTime( '2017-01-15' );
$dt->modify( 'next month' );
echo $dt->format( 'd-m-Y' );
// Resultado: 15-02-2017

See the examples online

answered by 20.09.2017 в 19:48
0

I would use date_add in conjunction with date_interval_create_from_date_string since it is very similar to DATE_ADD of MySQL:

$fecha = date_create('2016-01-01');
date_add($fecha, date_interval_create_from_date_string('1 month'));
echo $fecha->format('Y-m-d');
// Resultado: 2016-02-01

That's for procedures, although you can also use OOP:

$fecha = new DateTime('2016-01-01');
$fecha->add(new DateInterval('P1M'));
echo $fecha->format('Y-m-d') . "\n";

I hope it serves you. Greetings.

    
answered by 20.09.2017 в 20:24