insert date sequence in sequence in the bank

Asked

Viewed 75 times

1

I would like to enter the date in for it add + 1 day and insert again.

I have this script but it returns me random date:

date_default_timezone_set("Brazil/East");

$data = '2017-01-02';  
$data_fim='2017-01-09';

echo '<br />';
//faz a repeticao
for($i = 0; $i < $data_fim; $i++)
{
    // Soma 1 DIA

    echo $data = date('Y-m-d', strtotime($i . " days", strtotime($data)));

    echo '<br />';
}

echo '<br />';

kind of:

2017-01-02  
2017-01-03  
2017-01-05  
2017-01-08  
2017-01-12  
2017-01-17  
2017-01-23  
2017-01-30  
2017-02-07  
2017-02-16  
2017-02-26  
2017-03-09  
2017-03-21  
2017-04-03  
2017-04-17  
2017-05-02  
2017-05-18  
2017-06-04  
2017-06-22  
2017-07-11  
2017-07-31  
2017-08-21  

Can someone tell me what I’m doing wrong?

  • thanks friend worked !!,

  • it is generating date until year 2022 as wanted it from $initial date to $data_order

1 answer

1


Agree to compare an integer value $i with a string $data_fim doesn’t make any sense?

If you want to work with date ranges, you can use the native PHP class Datetime. First, setting the start and end dates:

$data_inicio = new DateTime('2017-01-02'); 
$data_fim = new DateTime('2017-01-09');

The class DateTime has a method called add to add dates, accepting an instance of DateInterval as parameter, which will define the time interval that will be added. To set a 1 day period, you can do:

$interval = new DateInterval("P1D");

The parameter P1D who is responsible for defining the. P means period and 1D the interval of 1 day.

To scroll through the dates then just loop:

for ($i = $data_inicio; $i <= $data_fim; $i->add($interval))
{
    echo $i->format("Y-m-d") . PHP_EOL;
}

The output of the program will be:

2017-01-02
2017-01-03
2017-01-04
2017-01-05
2017-01-06
2017-01-07
2017-01-08
2017-01-09

See working on Repl.it or in the Ideone.

  • I got it right away""""""""""""""""

  • @Sergiosilva, if you are new here, you can read the guide to how and why to accept an answer to know how to mark it as accepted. This will help in the organization of the community.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.