Date subtraction today - start date in PHP and bring result ex: 1 day 5hs and 25min

Asked

Viewed 138 times

0

I have 2 variables in PHP. The first is the order date $datarequested and the second is the date now $now. I need to list how long the order has been open.

$datapedido is consulted in MYSQL.

Both are in the same format: ('Y-m-d H:i').

I wanted, in php, to make an account of $now - $datapedido and have a result, for example, of 1 day, 5hs and 25min, if possible, already do this in the query of mysql so I can sort by what is the longest open.

  • You already have an answer on the subject: https://answall.com/questions/57/howto calculate a difference%C3%A7a-between-two-dates/70

  • 1

    The @Bacco response seems like a good suggestion that goes beyond mysql: How to humanize a date in PHP

1 answer

1


Table used

inserir a descrição da imagem aqui

Consultation held day 31/08 at 21:29hs from the server

SELECT
CONCAT(
TIMESTAMPDIFF(day,NOME_COLUNA,now()) , ' dias ',
MOD( TIMESTAMPDIFF(hour,NOME_COLUNA,now()), 24), ' hs ',
MOD( TIMESTAMPDIFF(minute,NOME_COLUNA,now()), 60), ' min '
) from NOME_TABELA

Upshot

inserir a descrição da imagem aqui

  • CONCAT function to join query values
  • TIMESTAMPDIFF - function to calculate the difference between dates

Order of consultation

For alphanumeric fields 10 comes before a 2 because the evaluation is done from left to right type by digit.

Table used:

inserir a descrição da imagem aqui

Upshot:

reult asc

With numeric values the default order is from the lowest to the highest, unless specified DESC in order by

To order the result, since it is always started by a number, you can convert the result of the query into a number that the sql will capture the part before the letters and convert to a number, then sort the result by this value.

Consultation:

SELECT
CONCAT(
TIMESTAMPDIFF(day,NOME_COLUNA,now()) , ' dias ',
MOD( TIMESTAMPDIFF(hour,NOME_COLUNA,now()), 24), ' hs ',
MOD( TIMESTAMPDIFF(minute,NOME_COLUNA,now()), 60), ' min '
) as resultado from NOME_TABELA ORDER BY CAST(resultado AS UNSIGNED INTEGER)

ordenada

  • Just one thing, I ordered and he understands that 10 days is less than 2 days (the order is 1, 10, 14, 2). How do I put in the right order? (1,2,10,14)

  • @Leandromarzullo, you can convert the result of the query into number that the sql will capture the part before the letters and convert to a number, then sort the result by this value. See edited response.

Browser other questions tagged

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