Finding the exact date by adding x days to the previous date

时间:2017-06-15 10:15:07

标签: php date

<?php
     $today = "2017-06-14";
     $prev = "1994-06-01";
     $date = $prev + //keep on adding 60 days till june,2017 
     echo '<br>' .$date;
?>

I also want to update the dates like this in database for 1000 entries! I want to have an Efficient, less time consumption methods?

1 个答案:

答案 0 :(得分:0)

以下是我将如何做到的......但是,您应该计划处理一个问题 - 如果2017年的60天增量超过6月会怎么样?我已经设置了一个演示来揭示这种情况:

代码(Demo):

$today=strtotime('today');
//$min=strtotime('first day of this month');
$max=strtotime('last day of this month');

$prevs=['1994-06-01','1994-06-7','1994-06-14','1994-06-15','1994-06-17','1994-06-21','1994-06-30'];
foreach($prevs as $prev){
    echo "prev = ",$prev = strtotime($prev),"\n";
    echo "diff = ",$diff=$today-$prev,"\n";  // calculate seconds between two dates
    // add just enough seconds (in 60 day increments) to reach at least $min
    echo "newseconds = ",$newseconds=$prev+5184000*ceil($diff/5184000),"\n"; // 60 days in seconds
    if($newseconds>$max){echo "Warning: new incremented date not in input month\n";}  // handle this exception?
    echo "newdate = ",date("Y-m-d",$newseconds),"\n\n";
}

输出:

prev = 770454000
diff = 727056000
newseconds = 1501398000
Warning: new incremented date not in input month
newdate = 2017-07-30

prev = 770972400
diff = 726537600
newseconds = 1501916400
Warning: new incremented date not in input month
newdate = 2017-08-05

prev = 771577200
diff = 725932800
newseconds = 1502521200
Warning: new incremented date not in input month
newdate = 2017-08-12

prev = 771663600
diff = 725846400
newseconds = 1502607600
Warning: new incremented date not in input month
newdate = 2017-08-13

prev = 771836400
diff = 725673600
newseconds = 1497596400
newdate = 2017-06-16

prev = 772182000
diff = 725328000
newseconds = 1497942000
newdate = 2017-06-20

prev = 772959600
diff = 724550400
newseconds = 1498719600
newdate = 2017-06-29