How to calculate the difference between two dates?

Asked

Viewed 59,467 times

51

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

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

6 answers

64


One of the ways to do this object-oriented, is by using the class Datetime, it has the method diff that returns an object Dateinterval, representing the interval between two separate dates:

Following the example of 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"; 
  • 3

    DateTime->diff() works from php 5.3. If you want the difference in days, use $intervalo->days.

29

You can also use the Mysql function DATEDIFF which is quite simple, see the examples:

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

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

Imagine 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, Voce can use:

SELECT DATEDIFF(ultimo_acesso, data_registro)

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

SELECT DATEDIFF( NOW(), ultimo_acesso)
  • I forgot to mention, if the date of the second parameter is greater than that of the first, the result will be negative.

  • 1

    One should be aware of the question tags, in case they have no tag related to Mysql, just quote in question, but no relation. But aggregate. :)

  • @JCM usually leave in the bank what I can, to relieve the logic of the application, but thank you

17

Solution available as of PHP 5.3+ version:

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

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

Exit:

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 can contain fewer fields if the version is lower.

16

return date_diff(date_create($data_fim), date_create($data_ini))->format('%d');//days
  • 2

    your response was flagged for poor quality due to size and content. Although it may be valid, try to develop a little more.

  • 1

    But what he typed doesn’t need more. It is perfect and it was what helped me, was the best response compared to the others who filled sausage code. Congratulations.

-4

$resultado = strtotime($data_inicial.' + '.$data_final);

-5

Follows code commented:

//adicionar as tags *PHP* **<?php** ao início e **?>** ao final do código
// substitua $pacientes['data']) pela data do nascimento ou pela primeira data, isto é, a mais antiga.

$data1 = date("Y-m-d", strtotime($pacientes['data'])); // data nascimento
$data2 = date("Y-m-d"); // data atual
$data2b = date('Y-m-d', strtotime('+1 year')); // data daqui um ano
$data3 = $data2b - date('z', strtotime($data2)); // primeiro dia próximo ano
$data3b = date('Y-m-d', strtotime('+1 month')); // data daqui um mês
$data4 = $data3b - date('z', strtotime($data2)); // primeiro dia próximo mês

$d1_ano = date('Y', strtotime($data1));
$d2_ano = date('Y', strtotime($data2));
$r_ano = $d2_ano - $d1_ano;
$d1_dia = ($d1_ano*365.25)+date('z', strtotime($data1));
$d2_dia = ($d2_ano*365.25)+date('z', strtotime($data2)); // z = nª dia/ano

$r_dia = $d2_dia - $d1_dia; //dias vividos desde nascimento

$r_ano = $r_dia / 365.25; //anos vividos desde nascimento

$r_mes = $r_ano*30; // meses vividos desde nascimento

$f1_ano = date('Y', strtotime($data1));
$f2_ano = date('Y', strtotime($data3));
$rf_ano = $f2_ano - $f1_ano;
$f1_dia = ($f1_ano*365.25)+date('z', strtotime($data1));
$f2_dia = ($f2_ano*365.25)+date('z', strtotime($data1));

$rf_dia = $f2_dia - $f1_dia; // dias p/ próximo aniversário

$rf_ano = $rf_dia / 365.25; // idade (ano) atual 

$f_dia = ($r_dia - $rf_dia); // idade (dia) atual ou dias vividos este ano

$f_mes = $f_dia/30; // idade (mês) atual ou meses vividos este ano


if($rf_ano <= 1) {
    $concordancia_ano = "ano";
} else {
    $concordancia_ano = "anos";
};

if($f_mes <= 1) {
    $concordancia_mes = "mês";
} else {
    $concordancia_mes = "meses";
};


echo floor($rf_ano); echo " "; echo $concordancia_ano; echo " e "; echo floor($f_mes); echo " "; echo $concordancia_mes; echo ".";

B'H all the knowledge.

Browser other questions tagged

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