Вопрос

I wrote a class in order to translate a date in different languages/format. I'm sorry, I repost this problem because last time I've posted it I lost my Internet connection and people left the thread...

Here is the full class...

class GetDateTime {

    private $_text_en_US = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", "January", "February", "March", "April", "May","June", "July", "August", "September","October", "November", "December");

    private $_text_fr_FR = array("Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche", "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre");

    public function getDateTime($format='d/m/Y', $timestamp, $locale='fr_FR') {
        switch ($format) {
            case 'd/m/Y':
            case 'm/d/Y':
                return date($format, $timestamp);
            break;  
            case 'l d F Y':
                return str_replace($_text_en_US, ${'_text_'.$locale}, date($format, $timestamp));
            break;  
        }
    }

}

...and how I call it :

include_once (BASE_DIR.'/lib/dateTime.class.php');
$dateTime = new GetDateTime();

The fact is it's not translated at all when I call :

echo $dateTime->getDateTime('l d F Y', time());
Это было полезно?

Решение 2

As the second argument of the getDateTime method you're expecting a timestamp but you're passing the result of date() function which is empty string. Replace it with time() function.

echo $dateTime->getDateTime('l d F Y', time());

EDIT:
How could I have missed that! You're refering to local variables, not object's properties. Use $this keyword in your last case condition:

return str_replace($this->_text_en_US, $this->{'_text_'.$locale}, date($format, $timestamp));

Другие советы

What about strftime? You can set your locale settings and get the translated date.

<?php
    setlocale(LC_TIME, "fr_FR");
    echo strftime("Today is %A (in French) and the date is %B %d, %Y");

    // Outputs something like that: Today is mercredi (in French) and the date is novembre 13, 2013
?>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top