如何使用 setlocale 将日期更改为西班牙语格式?

How to change date to spanish format with setlocale?

我尝试将月份名称更改为西班牙日期,但没有成功。我不知道是否需要在我的首页添加脚本。这是我的代码:

<tbody>
    <?php
    setlocale(LC_ALL,"es_ES");
    for($i = 1; $i <=12; $i++):
      $dt = DateTime::createFromFormat('!m', $i);
      ?>
      <tr>
        <td><?= $dt->format("F");?></td>
        <td></td>
        <td></td>
      </tr>
    <?php endfor;?>
</tbody>

试试这个:

<?php
setlocale(LC_TIME, 'es_ES', 'Spanish_Spain', 'Spanish');
$date = date('F j, Y');
echo strftime('%d %B %Y',strtotime($date));

首先,您必须确保您要使用的语言环境在您的系统上可用。 然后你必须使用一个使用语言环境的函数。 在我这里(ubuntu 桌面),我不得不

sudo locale-gen es_ES
sudo update-locale 

使用 strftime 函数获取非英语内容。

setlocale(LC_TIME,"es_ES");
for($i = 1; $i <=12; $i++){
      $dt = DateTime::createFromFormat('!m', $i);
      $time = mktime(0,0,0,$i);
    echo $dt->format("F") . " " . strftime('%B', $time) . " " . date('F', $time) . "\n";
}

给出以下输出:

January enero January
February febrero February
March marzo March
April abril April
May mayo May
June junio June
July julio July
August agosto August
September septiembre September
October octubre October
November noviembre November
December diciembre December

试试这个代码(详细解释见我的评论):

// Example date
$date = "2020-08-26"
// Set locale to Spanish
setlocale(LC_ALL, "es_ES.UTF-8");
// Transform the date to timestamp and then format to d-m-Y
$string = date("d-m-Y", strtotime($date));
// Create a new DateTimeObject
$date = \DateTime::createFromFormat("d-m-Y", $string);
// Get the timestamp from the previous object
// With strftime and the parameters (%B and %Y)
// %B - Full month name, based on the locale (agosto)
// %Y - Four digit representation for the year (2020)
// Returns a string (agosto 2020)
$date_humanized = strftime("%B %Y",$date->getTimestamp());