Subtract dates in PHP [duplicate]

this question already has answers here : diff, date_diff, abs-date calculation in PHP (2 responses) Closed 2 years ago .

I have a project where I need to change a piece of information from week to week.

Is there any automated PHP function that can help me subtract today's date by a base date I set. For example:

$datadehoje = (int)date("d/m/Y");
$database = (int)date("15/07/2018");
$resultado = $datadehoje - $database;

The above code is written in the wrong way but it is to exemplify more or less what I wanted. The project will have information for months and did not want to have to create its own algorithm for it.

 1
Author: Maniero, 2018-08-04

2 answers

There's no way to convert a date to int and get something meaningful. You have to make a difference using the date type itself to get a meaningful result, which will be a date range. Then you can get the amount of days that is a text, if you want you can convert that text to number if you are going to do accounts with it.

$database = date_create('2018-07-15');
$datadehoje = date_create();
$resultado = date_diff($database, $datadehoje);
echo date_interval_format($resultado, '%a');

I put on GitHub for reference future a.

 4
Author: Maniero, 2020-07-28 14:55:28

One of the ways to do an operation with dates in PHP is:

// a partir da data de hoje
echo date("d/m/Y",strtotime(date("Y-m-d")."+12 month"));

// a partir de outras datas
echo date("d/m/Y",strtotime(date("Y-m-d",strtotime($data_de_referencia))."-12 month"));

Reference date()

Reference strtotime()

 1
Author: Wees Smith, 2018-08-04 10:44:15