Convert String to date and remove 1 day from this String

2

I have this string:

$data_final = "26/11/2017";

And I need this variable to be 25/11/2017 . That is, I need to convert string to date and remove 1 day from that date.

    
asked by anonymous 21.11.2017 / 11:47

3 answers

3

Use the DateTime::createFromFormat method. Through this method it is possible to create a DateTime object from any format. Then, having the object created we use the modify method, which accepts as a parameter the same values as strtotime . At the end, we use the format method to get the date in the desired format.

See:

$data_final = '26/11/2017';

$ontem = DateTime::createFromFormat('d/m/Y', $data_final)->modify('-1 day');

echo $ontem->format('d/m/Y');

See an example running on Ideone

    
21.11.2017 / 12:10
4
$data = '26/11/2017';

$data = DateTime::createFromFormat('d/m/Y', $data);
$data->sub(new DateInterval('P1D')); // -1 dia
echo $data->format('d/m/Y');

I've used sub to remove the amount of days required, content HERE

Briefly, P symbolizes the period, 1 the amount of the period to be removed, and D symbolizes days.

    
21.11.2017 / 12:02
-1

If you ensure that the variable will always come in the xx / xx / xxxx format you can simply use explode followed by implode .

$data_final = explode("/","26/11/2017");

var_dump($data_final);

$data_final[0]--;

echo $data_final[0];

$data_final = implode("/",$data_final);

var_dump($data_final);

But I advise you to use the solution given by Comrade R.Santos

echo date('d/m/Y', strtotime('-1 days', strtotime('26-11-2017')));
    
21.11.2017 / 11:59