Subtract dates in PHP

Asked

Viewed 8,001 times

1

I’m with a project where I need to change information from week to week.

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

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

The code above is misspelled but is to illustrate more or less what I wanted. The project will have information for months and would not want to have to create an algorithm for this.

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

4

No way to convert a date into int and get something meaningful. You have to make a difference using the date type itself to get a significant 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 in the Github for future referenceto.

1

One of the ways to do an operation with dates on 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()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.