Ver Mensaje Individual
  #1 (permalink)  
Antiguo 22/04/2009, 08:57
Xixy
 
Fecha de Ingreso: enero-2009
Mensajes: 46
Antigüedad: 17 años, 8 meses
Puntos: 1
Calcular el tiempo pasado, horas/dias/semanas/ ago..".

Hola, seguro ya habrán visto aquel sistema en los comentarios para mostrar el tiempo pasado desde que se publicó.
Ejemplo:
"Hace 2 días"
"Hace 2 semanas"
etc.

En Youtube por ejemplo está presente, bueno y en muchos otros.

No encuentro la manera de hacerlo bien, incluso estuve probando funciones prefabricadas pero no hay manera, me tira cualquier dato.
Por ejemplo, la siguiente función.. a pesar de pasarle un "timestamp" reciente, el resultado es "hace 2 semanas".
Código PHP:
function timeDiff($timestamp){

        
$now = time();

        
//If the difference is positive "ago" - negative "away"
        
($timestamp >= $now) ? $action = 'away' : $action = 'ago';

        switch(
$action) {
        case 
'away':
                
$diff = $timestamp - $now;
                break;
        case 
'ago':
        default:
                
// Determine the difference, between the time now and the timestamp
                
$diff = $now - $timestamp;
                break;
        }

        
// Set the periods of time
        
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");

        
// Set the number of seconds per period
        
$lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);

        
// Go from decades backwards to seconds
        
for ($val = sizeof($lengths) - 1; ($val >= 0) && (($number = $diff / $lengths[$val]) <= 1); $val--);

        
// Ensure the script has found a match
        
if ($val < 0) $val = 0;

        
// Determine the minor value, to recurse through
        
$new_time = $now - ($diff % $lengths[$val]);

        
// Set the current value to be floored
        
$number = floor($number);

        
// If required create a plural
        
if($number != 1) $periods[$val].= "s";

        
// Return text
        
$text = sprintf("%d %s ", $number, $periods[$val]);
        return 
$text . $action;
} 
¿Entonces?, si alguien conoce alguna función eficiente o bien decirme que estoy haciendo mal, el por qué me lanza datos equivocados.

Gracias.

Última edición por Xixy; 23/04/2009 a las 10:36