deep
deep

Reputation: 23

Express time difference in a human readable format

On following function, I used 2 identical variables because inside is different language, I need help to replace this variable $periods[$j] .= "";

example:

function showdate($time)  
{  
    $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
    $periods2 = array("seconds", "minutes", "hours", "days", "weeks", "months", "years", "decade");
    $lengths = array("60","60","24","7","4.35","12","10");  
   
    $now = time();  
   
    $difference     = $now - $time;  
    $tense         = "ago";  
   
    for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++)   
    {  
        $difference /= $lengths[$j];  
    }  
   
    $difference = round($difference);  
   
    if ($difference != 1)   
    {
        **/* In this case, I need to show this variable: $periods2 */**  
        $periods[$j] .= "";
    }  
   
    return "$difference $periods[$j] $tense";  
}

Upvotes: 2

Views: 257

Answers (2)

JiminP
JiminP

Reputation: 2142

You can just write $periods[$j] = $periods2[$j], but I think making another variable is better.

function showdate($time){  
    $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
    $periods2 = array("seconds", "minutes", "hours", "days", "weeks", "months", "years", "decade");
    $lengths = array("60","60","24","7","4.35","12","10");  

    $now = time();  
    $difference = $now - $time;  
    $tense = "ago";

    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++)     
        $difference /= $lengths[$j];  

    $difference = round($difference);  
    $pText = $periods[$j];
    if($difference>1) $pText = $periods2[$j];
    return "$difference $pText $tense";  
}

Upvotes: 1

someone
someone

Reputation: 1468

if($difference != 1)   
{
     $periods[$j] = $periods2[$j];
}  

Also, decade in your periods2 array is missing an s.

Upvotes: 0

Related Questions