Adding days to $Date in PHP

前端 未结 9 2124
时光取名叫无心
时光取名叫无心 2020-11-22 09:32

I have a date returned as part of a mySQL query in the form 2010-09-17

I would like to set the variables $Date2 to $Date5 as follows:

$Dat

9条回答
  •  暖寄归人
    2020-11-22 10:17

    If you're using PHP 5.3, you can use a DateTime object and its add method:

    $Date1 = '2010-09-17';
    $date = new DateTime($Date1);
    $date->add(new DateInterval('P1D')); // P1D means a period of 1 day
    $Date2 = $date->format('Y-m-d');
    

    Take a look at the DateInterval constructor manual page to see how to construct other periods to add to your date (2 days would be 'P2D', 3 would be 'P3D', and so on).

    Without PHP 5.3, you should be able to use strtotime the way you did it (I've tested it and it works in both 5.1.6 and 5.2.10):

    $Date1 = '2010-09-17';
    $Date2 = date('Y-m-d', strtotime($Date1 . " + 1 day"));
    // var_dump($Date2) returns "2010-09-18"
    

提交回复
热议问题