How to convert "month" to "months" using PHP timestamp?

Asked

Viewed 102 times

0

Here’s the code:

function longadata($data)
{
    if(empty($data)) 
    {
        return "No date provided";
    }

    $periods         = array(_segundo, _minuto, _hora, _dia, _semana, _mes, _ano, _decada);
    $lengths         = array("60", "60", "24", "7", "4.35", "12", "10");

    $now             = time();
    $unix_date       = strtotime($data);

    if (empty($unix_date)) 
    {    
        return "Bad date";
    }

    if ($now > $unix_date) 
    {    
        $difference     = $now - $unix_date;
        $tense          = _atras;   
    } 

    else 
    {
        $difference     = $unix_date - $now;
        $tense          = _agora;
    }

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

    $difference = round($difference);

    if($difference != 1) 
    {
        $periods[$j].= "s";
    }

    return "$difference $periods[$j] {$tense}";
}

In HTML:

<li class="published-date"><?php echo longadata("2017-08-28") ?></li>

In the result:

3 MÊSS ATRÁS

I want to fix from "month" to "months" by code, but I have to keep those codes because of "second", "minute", "year", etc.:

if($difference != 1) 
 {
   $periods[$j].= "s";
 }

2 answers

0

From what I understand the answer seems to me to be too obvious, but I believe not to be that, good in any case... In this part I think you just need to put a "and":

if($difference != 1) 
 {
   $periods[$j].= "es";
 }

the output will be:

3 _meses _atras

I don’t know if that was the problem, but if you don’t try to explain it better,!

  • but in this code, it appeared as second, minute, ...

0


You can check if the last letter is s or if the $j is 5:

if($difference !== 1){
    $periods[$j] .= mb_substr($periods[$j], -1, 1) === 's' ? 'es' : 's';
}

The other way would be:

if($difference !== 1){
    $periods[$j] .= $j === 5 ? 'es' : 's';
}

If there is an accent in "month" this has to be removed, you can simply remove all accents using the strtr, for example:

if($difference !== 1){
    $periods[$j] .= $j === 5 ? 'es' : 's';
    $periods[$j] = str_replace('ê', 'e', $periods[$j]);
}
  • The 3rd code is fine, thank you. I have a question. If the site is in English or French? For example: if($difference !== 1)&#xA;{&#xA; if ($language == "pt_BR")&#xA; {&#xA; $periods[$j] .= $j === 5 ? 'es' : 's';&#xA; $periods[$j] = str_replace('ê', 'e', $periods[$j]);&#xA; }&#xA;&#xA; if ($language == "en_GB")&#xA; {&#xA; $periods[$j].= "s";&#xA; }&#xA;}&#xA;

  • I managed to solve the multilingual function case.

Browser other questions tagged

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