How to calculate the difference between two dates?

46

What is the most practical way to find the time difference between two dates in the standard format used by MySQL (YYYY-MM-DD)? Ex:

Date 1: 2013-12-11 Date 2: 1994-04-17

    
asked by anonymous 11.12.2013 / 17:59

5 answers

56

One of the ways to do this object-oriented, is by using the DateTime class , the it has the diff method that returns an object DateInterval , which represents the interval between two distinct dates:

Following the example dates:

$data1 = new DateTime( '2013-12-11' );
$data2 = new DateTime( '1994-04-17' );

$intervalo = $data1->diff( $data2 );

echo "Intervalo é de {$intervalo->y} anos, {$intervalo->m} meses e {$intervalo->d} dias"; 
    
11.12.2013 / 17:59
24

You can also use the MySQL function DATEDIFF that is quite simple, see the examples:

SELECT DATEDIFF('2013-01-01','2012-03-01')

In the case above, I have passed two dates "manually", they can be two fields:

Imagine that you have a table with the fields data_registro and ultimo_acesso , if you want to show the user the number of days between the registration and the last access, you can use:

SELECT DATEDIFF(ultimo_acesso, data_registro)

If you need to calculate the difference between any date and current date, you can use the NOW () (en)

SELECT DATEDIFF( NOW(), ultimo_acesso)
    
11.12.2013 / 18:22
14

Solution available from PHP version 5.3+:

$date  = new DateTime('2012-12-25 12:00:00');
$date2 = new DateTime('2013-12-25 12:00:00');

var_dump($date->diff($date2));

Output:

object(DateInterval)[3]
  public 'y' => int 1
  public 'm' => int 0
  public 'd' => int 0
  public 'h' => int 0
  public 'i' => int 0
  public 's' => int 0
  public 'weekday' => int 0
  public 'weekday_behavior' => int 0
  public 'first_last_day_of' => int 0
  public 'invert' => int 0
  public 'days' => int 365
  public 'special_type' => int 0
  public 'special_amount' => int 0
  public 'have_weekday_relative' => int 0
  public 'have_special_relative' => int 0

I'm using php 5.5.7 here, so this output may contain fewer fields if the version is lower.

    
13.12.2013 / 14:26
13
return date_diff(date_create($data_fim), date_create($data_ini))->format('%d');//days
    
03.12.2014 / 16:50
-3
$resultado = strtotime($data_inicial.' + '.$data_final);
    
20.02.2018 / 18:06