Convert seconds in days

4

I have a very simple question: How to convert seconds into days? tried using:

<?php echo date('d', $userstats['OnlineTime']); ?>

but goes only up to 31 days.

<?php
   $userstats_a = mysql_query("SELECT * FROM user_stats INNER JOIN users ON user_stats.id = users.id WHERE users.Rank <5 ORDER BY user_stats.OnlineTime DESC LIMIT 5");

   while($userstats = mysql_fetch_assoc($userstats_a)){
   ...
    
asked by anonymous 11.11.2017 / 20:39

3 answers

4

One day has 86400 seconds (60 * 60 * 24).

To convert seconds into days:

$dias = $segundos / 86400;

If you do not want decimals, rounding down:

$dias = floor( $segundos / 86400 );

rounding up:

$dias = ceil( $segundos / 86400 );


Main rounding functions manual:

  

link

     

link

     

link

    
12.11.2017 / 01:15
1

You can do an operation on SELECT itself:

SELECT OnlineTime / 60 / 24 AS Tempo FROM user_stats INNER JOIN users ON user_stats.id = users.id WHERE users.Rank <5 ORDER BY user_stats.OnlineTime DESC LIMIT 5 
    
11.11.2017 / 20:47
-2

You can get the expected result using the DateTime class, see example:

We've created a feature to make it easier to use:

function converterSegundos($segundos, $formato) {
    $dtF = new \DateTime('@0');
    $dtT = new \DateTime("@$segundos");
    return $dtF->diff($dtT)->format($formato);
}

Now to use just call the function informing a format, below it returns in seconds.

// 6 segundos
echo converterSegundos(6, '%s segundos');

Now only minutes:

// 6 minutos
echo converterSegundos(369, '%i minutos');

You can return the time:

// 10 horas
echo converterSegundos(36000, '%h horas');

You can return the days:

// 60 dias
echo converterSegundos(5184000, '%a dias');

Or

// 60 dias, 0 horas, 0 minutos e 0 segundos
echo converterSegundos(5184000, '%a dias, %h horas, %i minutos e %s segundos');
  

See working at repl.it

Reference

11.11.2017 / 22:58