20

I'm trying to create a conditional translation of the PHP internal date() function. Is it possible to somehow redefine the internal variables - e.g. - date('M'), date('y') etc so that different strings are fed into the remainder of the PHP function on the basis of this test:

if (ICL_LANGUAGE_CODE == 'fr') { }

The following is a working example of the code I'm using for a dates module. Since $date is defined with many variables contained in this definition it's important to conditionally re-define the variables within PHP's date() first in order to avoid having to redefine the variable 100 times or more within each key.

if($start <= $end):
    if($start == $end):
        //Month Day, Year
        $date =  date('F', $start).' '.date('j',$start).', '.date('Y', $start);
    else:
        if($start_year == $end_year):
            if($start_month == $end_month):

                //Month Day - Day, Year
                $date = date('F', $start).' '.date('j',$start).' - '.date('j', $end).', '.date('Y', $start);
            else:
                //Month Day - Month Day, Year
                $date =  date('F', $start).' '.date('j',$start).' - '.date('F', $end).' '.date('j', $end).', '.date('Y', $start);
            endif;
        else:
            //Month Day, Year - Month Day, Year
            $date =  date('F', $start).' '.date('j',$start).', '.date('Y', $start).' - '.date('F', $end).' '.date('j', $end).', '.date('Y', $end);
        endif;
    endif;
endif;
hakre
  • 193,403
  • 52
  • 435
  • 836
Brian
  • 3,920
  • 12
  • 55
  • 100

4 Answers4

36

Whenever you need to manipulate date/time stamps based on locale, you should use strftime:

switch ($lang) {
    case 'en':
        setlocale(LC_TIME, 'en_CA.UTF-8');
        echo strftime("%B %e, %G");
        break;
    case 'fr':
        setlocale(LC_TIME, 'fr_CA.UTF-8');
        echo strftime("%e %B %G");
        break;
}

Results:

February 11, 2011  // en
11 février 2011    // fr

Of course, you need to have the locales installed on your system. In Ubuntu per example:

bash-4.1$ sudo locale-gen fr_CA.UTF-8

EDIT in may 2022

strftime() has been DEPRECATED as of PHP 8.1.0

This is how you should do it:

$fmt = datefmt_create(
    'pt_BR', // The output language.
    \IntlDateFormatter::FULL,
    \IntlDateFormatter::FULL,
    pattern: "cccc, d 'de' LLLL 'de' YYYY" // The output formatting.
);
$input = strtotime('20-06-2022');
$output = datefmt_format($fmt, $input);

var_dump($output); // Outputs "segunda-feira, 20 de junho de 2022".

As for strtotime() use:

  • slash (/) for American M/D/Y formatting;
  • dash (-) for European D-M-Y formatting and
  • period (.) for ISO Y.M.D formatting.

In my sample I am using the european day-month-year formatting.

Click here to see how to format the value of $pattern parameter in datefmt_create().

You must have the intl package installed:

$ sudo apt install php8.1-intl

Change the 8.1 bit to the php version you are working with.

Francisco Luz
  • 2,775
  • 2
  • 25
  • 35
netcoder
  • 66,435
  • 19
  • 125
  • 142
8
    $date =  date('F', $start).' '.date('j',$start).', '.date('Y', $start);

That's a rather painful way to go about. The format string in date() doesn't have to be a single character. This line could be reduced to

$date = date('F j Y');

And given that, you could have a simple

switch($whats_my_locale) {
    case 'FR':
       $format = 'date format characters for a french date';
       break
    case 'EN' :
       $format = 'format chars for english date'
       break
    case etc....
    default:
       $format = 'default date format string here';
}

$local_date_string = date($format, $start);

and off you go.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • This looks great, my question is - in the context of `$format = 'date format characters... fr';` how are these variables (e.g. 'm', 'd', 'M') etc. being re-defined to French? – Brian Feb 12 '11 at 02:17
  • And my apologies for being dense! :( – Brian Feb 12 '11 at 02:17
  • The `date()` man page (http://php.net/date) says to use `setlocale()` and `strftime()` for non-english dates. But the same format string rules basically apply there - it doesn't have to be a single char, it can be a string of formatting chars. – Marc B Feb 12 '11 at 02:21
0

I'm sure you have, but have you considered just using the numeric values?

Also, if you do use them, remember the US has months / day, opposite to the UK and others.

Jake Lee
  • 7,549
  • 8
  • 45
  • 86
  • That's a thought. I definitely hope to avoid this but it did escape me... I'll count this as a backup plan. Thanks. – Brian Feb 12 '11 at 02:20
  • Yeah, it is nicer to have a full date, but users would definitely prefer a functional numeric one. Heck, you could even just use a random javascript date. – Jake Lee Feb 12 '11 at 02:23
0

I was looking for this lately and I found out a way to translate datetime in php.

Let's take the fr example

  • First I created a new Class that extend GlobalDateTime

in App\Core\DateTime.php

    namespace App\Core;
    
    use DateTime as GlobalDateTime;
    
    class DateTime extends GlobalDateTime
    {
        public function __construct($str_date = "now")
        {
            parent::__construct($str_date);
        }
    
        public function toLocalTimeString(): string
        {
            $Y = $this->format('Y');
            $M = $this->_get('month', $this->format('m'));
            $l = $this->_get('day', $this->format('l'));
            $d = $this->format('d');
            $H = $this->format('H');
            $i = $this->format('i');
    
            return "$l $d $M $Y à $H:$i";
        }
    
        private function _get($key, $id): string
        {
            return [
                'day' => [
                    0 => "Dim",
                    1 => "Lun",
                    2 => "Mar",
                    3 => "Mer",
                    4 => "Jeu",
                    5 => "Ven",
                    6 => "Sam",
                    "Sun" => "Dim",
                    "Mon" => "Lun",
                    "Tue" => "Mar",
                    "Wed" => "Mer",
                    "Thu" => "Jeu",
                    "Fri" => "Ven",
                    "Sat" => "Sam",
                    "Sunday" => "Dimanche",
                    "Monday" => "Lundi",
                    "Tuesday" => "Mardi",
                    "Wednesday" => "Mercredi",
                    "Thursday" => "Jeudi",
                    "Friday" => "Vendredi",
                    "Saturday" => "Samedi",
                ],
                'month' => [
                    "01" => "Jan",
                    "02" => "Fév",
                    "03" => "Mar",
                    "04" => "Avr",
                    "05" => "Mai",
                    "06" => "Juin",
                    "07" => "Juil",
                    "08" => "Aôut",
                    "09" => "Sept",
                    "10" => "Oct",
                    "11" => "Nov",
                    "12" => "Déc",
                ],
            ][$key][$id];
        }
    }
  • And then I can call it wherever I want like

use App\Core\DateTime;

$datetime = new DateTime('now');
$strdatetime = $datetime->toLocalTimeString(); // return vendredi 18 Aôut 2022 à 08:00
  • You can custom this DateTime class as you like

I hope this will help you.