简体   繁体   中英

PHP Change date variable after x days

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

PS sorry for my bad English.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM