PHP Change date variable after x days

171 views Asked by At

I want to change date var when x days have passed

For instance:

Today is 21.12.16 - $date = '23.12.16'

Tomorrow is 22.12.16 - $date = '23.12.16'

When it's 23.12.16 - $date = '25.12.16'

Her's the code I got so far. Hope this will make some sense

   $date            = "2016-12-21"; //** will describe this lower
   $days_passed = date_create()->diff(date_create($date))->days;
if ($days_passed >= 2){
    $new_date = date('d.m.y', strtotime("+2 days"));
} else{
    $new_date = $date;
}

This works ok if I just want to do it once

**I need to change this var every 2 days. I understand that i can write it to a Database or to a .txt. But there sure is a way to do this just by php

P.S. sorry for my bad English.

1

There are 1 answers

0
Serij  Fragio On BEST ANSWER

Here's what I came up with:

$date           = '2016-12-01';  //Your script start date, you wont need to change this anymore
$everyxdate     = 10; // once x days to add x to $date
$days_passed    = date_create()->diff(date_create($date))->days; // passed days from start of script $date

$mod_dates = (int)($days_passed / $everyxdate); // count how much cycles have passed
$daystoadd = $mod_dates * $everyxdate + $everyxdate;  // count how much days we need to add
$newdate = strtotime ("+$daystoadd day" , strtotime ( $date ) ) ; // Add needed day count to starting $date 
$newdate = date ( 'd.m.y' , $newdate ); // Format date the way you want

Hope this will help some one who has the same task I had.