Add days to a date

I need to add another 2 days on a date coming from a variable.

I'm doing this way but it's not working.

$data = '17/11/2014';
echo date($data, strtotime("+2 days"));
 21
Author: Maniero, 2014-11-17

3 answers

I already managed to do what I wanted. I'll leave the code here for other people to use.

$data = "20-10-2014"; 
echo date('d/m/Y', strtotime("+2 days",strtotime($data))); 
 33
Author: Lucas William, 2014-11-17 13:44:57

Your problem is in using the strtotime(). You need to say on top of what you want to add up to 2 days. You were just adding 2 days to nothing. In addition to this you need to specify in what format you want the new date so as not to run the risk of leaving in an unwanted way.

$data = "17/11/2014";
echo date('d/m/Y', strtotime($data. ' + 2 days'));

See working on ideone. E no repl.it. also I put on GitHub for future reference .

 12
Author: Maniero, 2020-09-11 11:51:52

Another way to accomplish this task is to use the Class DateTime and spend the period to be added to the date, it is specified in the constructor of DateInterval , it must start with P (of period) and followed by a number last the unit:

Y | Ano
M | Mês
D | Dias
W | Semanas
H | Horas
M | Minutos
S | Segundos  

Note that month and Minute use the same letter M. For the parse to be done correctly the largest unit(s) must be to the left.

For values containing hours, minutes, or seconds the letter T should be used to signal this excerpt.


<?php

$data = '17/11/2014';

$data = DateTime::createFromFormat('d/m/Y', $data);
$data->add(new DateInterval('P2D')); // 2 dias
echo $data->format('d/m/Y');

Example

 11
Author: rray, 2017-08-22 20:06:55