Em PHP, o método diff()
da classe DateTime
é capaz de calcular a diferença entre duas datas:
$agora = new DateTime();
$data = new DateTime('2020-01-25 12:21:33');
var_dump( $agora->diff($data) );
Saída:
object( DateInterval )#3 (15)
{
["y"]=> int(2)
["m"]=> int(5)
["d"]=> int(24)
["h"]=> int(2)
["i"]=> int(45)
["s"]=> int(0)
["weekday"]=> int(0)
["weekday_behavior"]=> int(0)
["first_last_day_of"]=> int(0)
["invert"]=> int(0)
["days"]=> int(907)
["special_type"]=> int(0)
["special_amount"]=> int(0)
["have_weekday_relative"]=> int(0)
["have_special_relative"]=> int(0)
}
Em Postgres:
-- Diferenca total em Segundos
SELECT extract(epoch from ('2020-01-25 12:21:33' - now()));
-- Diferenca por partes:
SELECT
date_part( 'year', age('2020-01-25 12:21:33',now()) ) AS qtd_anos,
date_part( 'month', age('2020-01-25 12:21:33',now()) ) AS qtd_meses,
date_part( 'day', age('2020-01-25 12:21:33',now()) ) AS qtd_dias,
date_part( 'hour', age('2020-01-25 12:21:33',now()) ) AS qtd_horas,
date_part( 'minute', age('2020-01-25 12:21:33',now()) ) AS qtd_minutos,
date_part( 'second', age('2020-01-25 12:21:33',now()) ) AS qtd_segundos;
date
com umtimestamp
vindo do banco de dados, o que vai tornar o problema numa diferença normal de datas em phpSELECT '2017-08-01 09:30:00'::TIMESTAMP - TO_CHAR(now(), 'yyyy-mm-dd HH:I:S')::TIMESTAMP;