首页 > 解决方案 > 将月份名称格式化为当地语言

问题描述

我做了一个预订系统,现在我的月份名称有问题。在这种情况下,它是英文的,我想使用葡萄牙语。

我尝试在语句中使用setlocale(LC_ALL, 'pt_BR')and 。strftimemktime

setlocale(LC_ALL, 'pt_BR');
    
     // Create array containing abbreviations of days of week.
     $daysOfWeek = array('Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado');

     // What is the first day of the month in question?
     $firstDayOfMonth = mktime(0,0,0,$month,1,$year);

     // How many days does this month contain?
     $numberDays = date('t',$firstDayOfMonth);

     // Retrieve some information about the first day of the
     // month in question.
     $dateComponents = getdate($firstDayOfMonth);

     // What is the name of the month in question?
     $monthName = $dateComponents['month'];

     // What is the index value (0-6) of the first day of the
     // month in question.
     $dayOfWeek = $dateComponents['wday'];

     // Create the table tag opener and day headers
     
    $datetoday = date('Y-m-d');
    
    
    
    $calendar = "<table class='table table-bordered'>";
    $calendar .= "<center><h2>$monthName $year</h2>";
    $calendar.= "<a class='btn btn-xs btn-primary' href='?month=".date('m', mktime(0, 0, 0, $month-1, 1, $year))."&year=".date('Y', mktime(0, 0, 0, $month-1, 1, $year))."'>Mês Anterior</a> ";
    
    $calendar.= " <a class='btn btn-xs btn-primary' href='?month=".date('m')."&year=".date('Y')."'>Atual Mês</a> ";
    
    $calendar.= "<a class='btn btn-xs btn-primary' href='?month=".date('m', mktime(0, 0, 0, $month+1, 1, $year))."&year=".date('Y', mktime(0, 0, 0, $month+1, 1, $year))."'>Próximo Mês</a></center><br>";

如您所见,$dayOfWeek它具有从星期日到星期六的日期名称,并且在按钮中,文本分别包含上个月、当前月份和下个月。

谁能帮我在哪里插入strftime以翻译月份名称?我在每个地方都尝试过,但总是出错或日历停止工作。

更新:所以,我在代码中添加了一些行,但我仍然无法翻译月份名称

// What is the name of the month in question?
$monthName = $dateComponents['month'];

setlocale(LC_TIME, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
date_default_timezone_set('America/Sao_Paulo');
echo strftime('%B %Y', strtotime($monthName));

我得到的只是三月而不是马尔科。

我让它工作了,但是像ç这样的一些特殊字符不起作用:

mar�o 2021

SOLUTION : utf8_encode 解决了这个问题

// What is the name of the month in question?
$monthName = $dateComponents['month'];

setlocale(LC_TIME, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
date_default_timezone_set('America/Sao_Paulo');
echo utf8_encode(strftime('%B %Y', strtotime($monthName)));

标签: phptranslate

解决方案


首先,您不应该在没有\LC_ALL特定原因的情况下使用,因为您只想更改\LC_TIME. 因此,您应该使用\setlocale(\LC_TIME, 'pt_BR');.

也不要忘记设置您的默认时区:

\date_default_timezone_set('America/Sao_Paulo');

你还说,你总是会出错。为了帮助您,我们需要错误消息。


推荐阅读