PHP Calculating future date by adding days to a variable date

Posted on

PHP Calculating future date by adding days to a variable date – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and math . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about PHP Calculating future date by adding days to a variable date.

I was looking at this post, and it is close to what I need:
PHP – How to count 60 days from the add date

However, in that post, the calculation is performed by adding 60 days to the current date. What I need to do is calculate the date based on a variable date (and not the current date).

Something like this:

$my_date = $some_row_from_a_database;
$date_plus_10_days = ???;

Anyone know how to do that?


Solution :

You can put something before the “+10 days” part:

strtotime("2010-01-01 +10 days");

Use date_add

$my_date = new DateTime($some_row_from_a_database);
$date_plus_10_days = date_add($my_date, new DateInterval('P10D'));

You will have to look into strtotime(). I’d imagine your final code would look something like this:

$dateVariable      = strtotime('2017-01-29');//your date variable goes here
$date_plus_60_days = date('Y-m-d', strtotime('+ 60 days', $dateVariable));
echo $date_plus_60_days;

If you are using PHP >= 5.2 I strongly suggest you use the new DateTime object. For example like below:

$date_plus_60_days = new DateTime("2006-12-12");
$date_plus_60_days->modify("+60 days");
echo $date_plus_60_days->format("Y-m-d");

I see you are retriving data from a database.
If you are using mysql you can do it on the select:

Example: you need the last date of the table and this date-7 days

select max(datefield) as ultimaf, DATE_SUB(max(datefield),INTERVAL 7 DAY) as last7
from table

It´s easy use curdate() if you want todays date.

If you need a dynamic between that selects the count of last 7 days:

select count(*) from table
where DATE_SUB(CURDATE(),INTERVAL 7 DAY)<=datefield"

date('Y-m-d H:i:s', strtotime("2014-11-24 06:33:39" +35 days"))

this will get the calculated date in defined format.

Suppose today’s date is


And i can add 10 days in current date as follows :

$date_afte_10_days = date('Y-m-d', strtotime("$today +10 days"));

Leave a Reply

Your email address will not be published. Required fields are marked *