Adding days to $Date in PHP

Viewed 574980

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:

$Date2 = $Date + 1

$Date3 = $Date + 2

etc..

so that it returns 2010-09-18, 2010-09-19 etc...

I have tried

date('Y-m-d', strtotime($Date. ' + 1 day'))

but this gives me the date BEFORE $Date.

What is the correct way to get my Dates in the format form 'Y-m-d' so that they may be used in another query?

12 Answers

This works. You can use it for days, months, seconds and reformat the date as you require

public function reformatDate($date, $difference_str, $return_format)
{
    return date($return_format, strtotime($date. ' ' . $difference_str));
}

Examples

echo $this->reformatDate('2021-10-8', '+ 15 minutes', 'Y-m-d H:i:s');
echo $this->reformatDate('2021-10-8', '+ 1 hour', 'Y-m-d H:i:s');
echo $this->reformatDate('2021-10-8', '+ 1 day', 'Y-m-d H:i:s');

To add a certain number of days to a date, use the following function.

function add_days_to_date($date1,$number_of_days){
    /*
    //$date1 is a string representing a date such as '2021-04-17 14:34:05'
    //$date1 =date('Y-m-d H:i:s'); 
    // function date without a secrod argument returns the current datetime as a string in the specified format
    */
    $str =' + '. $number_of_days. ' days';
    $date2= date('Y-m-d H:i:s', strtotime($date1. $str));
    return $date2; //$date2 is a string
}//[end function]

Another option is to convert your date string into a timestamp and then add the appropriate number of seconds to it.

$datetime_string = '2022-05-12 12:56:45';
$days_to_add = 1;
$new_timestamp = strtotime($datetime_string) + ($days_to_add * 60 * 60 * 24);

After which, you can use one of PHP's various date functions to turn the timestamp into a date object or format it into a human-readable string.

$new_datetime_string = date('Y-m-d H:i:s', $new_timestamp);
Related