2

Supuestamente en la web, la siguiente línea de código setlocale(LC_TIME,"es_ES"); convertía todo en español, pero no es así, no se que otro parámetro se debe agregar.

actualmente la siguiente línea $calendar .= '<h2 class="monthYear">'.strftime($monthName).' '.$year.'</h2>'; me imprime November 2020 lo que deseo es poder cambiar el idioma fácilmente así como date_default_timezone_set que me determina una zona horaria según los parámetros o datos que se le agreguen.

Dado a lo que deseo conseguir en el código, como puedo hacer que dicha función setlocale(LC_TIME,"es_ES"); o que otro cambio debo agregar o corregir para poder cambiar el idioma globalmente.

Este es mi código

<?php
    
    date_default_timezone_set('America/Guayaquil');
    setlocale(LC_TIME,"es_ES");

    //Check date register
    function checkSlots(){
        $TotalBookings = 0;
        return $TotalBookings;
    }

    //Print calendar //$month = 11; //$year = 2020;
    function BuildCalendar($month, $year){

        //Lunes martes Miércoles Jueves Viernes Sábado Domingo // Monday Tuesday Wednesday Thursday Friday Saturday Sunday
        // Create array containing abbreviations of days of week.
        $daysOfWeek = array('LUN.','MAR.','MIÉ.','JUE.','VIE.','SÁB.','DOM.');
        // 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'];

        if($dayOfWeek==0){
            $dayOfWeek = 6;
        } else {
            $dayOfWeek = $dayOfWeek-1;
        }

        // Create the table tag opener and day headers
        $datetoday = date('Y-m-d');

        $calendar = "<table class='table-calendar'>";
        $calendar .="<center>";
        $calendar .= '<h2 class="monthYear">'.strftime($monthName).' '.$year.'</h2>';
        
        //btn btn-xs btn-primary
        //$calendar.= "<a class='changemonth' data-target='?month=".date('m', mktime(0, 0, 0, $month-1, 1, $year))."&year=".date('Y', mktime(0, 0, 0, $month-1, 1, $year))."'>Mes anterior</a> ";
        //$calendar.= " <a class='changemonth' data-target='?month=".date('m')."&year=".date('Y')."'>Mes actual</a> ";
        //$calendar.= "<a class='changemonth' data-target='?month=".date('m', mktime(0, 0, 0, $month+1, 1, $year))."&year=".date('Y', mktime(0, 0, 0, $month+1, 1, $year))."'>Mes siguiente</a><br>";
        
        $calendar .="</center>";
        $calendar .= "<tr>";

        // Create the calendar headers
        foreach($daysOfWeek as $day) {
            $calendar .= "<th  class='header_weekday'>$day</th>";
        }

        // Create the rest of the calendar
        // Initiate the day counter, starting with the 1st.
        $currentDay = 1;
        $calendar .= "</tr><tr>";

        // The variable $dayOfWeek is used to
        // ensure that the calendar
        // display consists of exactly 7 columns.
        if ($dayOfWeek > 0) {
            for($k=0;$k<$dayOfWeek;$k++){
                $calendar .= "<td  class='empty'></td>";
            }
        }

        $month = str_pad($month, 2, "0", STR_PAD_LEFT);

        while ($currentDay <= $numberDays) {
            // Seventh column (Saturday) reached. Start a new row.
            if ($dayOfWeek == 7) {
                $dayOfWeek = 0;
                $calendar .= "</tr><tr>";
            }

            $currentDayRel = str_pad($currentDay, 2, "0", STR_PAD_LEFT);
            $date = "$year-$month-$currentDayRel";
            $dayName = strtolower(date('l', strtotime($date)));
            //$eventNum = 0;
            $today = $date==date('Y-m-d')? "today" : "";

            if ($date<date('Y-m-d')) {
                $calendar.="<td class='$today'><h4>$currentDay</h4> <button class='btn-danger'>N/A</button>";
            } elseif($dayName=='monday' || $dayName=='tuesday' || $dayName=='wednesday' || $dayName=='thursday' || $dayName=='friday') {
                $TotalBookings = checkSlots();
                if($TotalBookings==4) {
                    $calendar.="<td class='$today'><h4>$currentDay</h4> <a href='#' class='btn-danger'>Reservado</a>";
                } else {
                    $availableslots = 4 - $TotalBookings;
                    $calendar.="<td class='$today'><h4>$currentDay</h4> <a id='dateCalendar' class='dateCalendar' data-target='".$date."'>Disponible</a> <small><i>$availableslots Turnos</i></small>";
                }

            }elseif($dayName=='saturday' || $dayName=='sunday') {

                $TotalBookings = checkSlots();
                if($TotalBookings==4) {
                    $calendar.="<td class='$today'><h4>$currentDay</h4> <a href='#' class='btn-danger'>Reservado</a>";
                } else {
                    $availableslots = 4 - $TotalBookings;
                    $calendar.="<td class='$today'><h4>$currentDay</h4> <a id='dateCalendar' class='dateCalendar' data-target='".$date."'>Disponible</a> <small><i>$availableslots Turnos</i></small>";
                }
            }

            $calendar .="</td>";

            // Increment counters
            $currentDay++;
            $dayOfWeek++;
        }

        if($daysOfWeek<7){
            $remainingDays = 7 - $dayOfWeek;
            for($i=0;$i<$remainingDays;$i++){
                $calendar .= "<td class='empty'></td>";
            }
        }

        $calendar .= "</tr>";
        $calendar .= "</table>";

        return $calendar;

    }

    #Print rows date //$_GET
    $dateComponents = getdate();
    if(isset($_GET['month']) && isset($_GET['year'])){
        $month = $_GET['month'];
        $year = $_GET['year'];
    }else{
        $month = $dateComponents['mon'];
        $year = $dateComponents['year'];
    }

    echo BuildCalendar($month, $year);
?>
<style type="text/css">
    .today {
        background-color: yellow;
    }
</style>

2 respuestas 2

1

Pues, no es mucho lo que hay que cambiar en realidad.
Lancé tu código, y edite un par de cosas:

- Por algún motivo, setlocale() no funciona bien con "es_ES", asi que solo usa "es"

setlocale(LC_TIME,"es");

- El otro problema, es que no estás aplicando strftime() correctamente.
Para que funcione debidamente, debe tener el cambio de formato respectivo,
en este caso, quieres el mes con respecto a setlocale() ("%B")
Pero además de eso, le estás pasando un string el cual es el mes, para que ese mes se respete, debes parsearlo a time. Al final quedaría algo como esto:

$calendar .= '<h2 class="monthYear">'.strtoupper(strftime("%B", strtotime($monthName))).' '.$year.'</h2>';

Finalmente, el resultado que estoy obteniendo con esto es:

introducir la descripción de la imagen aquí

1

He intentado reducir tu ejemplo a la mínima expresión, ya que hay muchas cosas que no nos interesan:

setlocale(LC_TIME,"es_ES");
$dateComponents = getdate();
$month = $dateComponents['mon'];
$year = $dateComponents['year'];

$firstDayOfMonth = mktime(0,0,0,$month,1,$year);

$monthName = $dateComponents['month'];


echo strftime($monthName);

El problema aquí es que strftime espera una cadena con marcas y un timestamp. Y tu solo le estás pasando "November" que no significa nada para la función.

Un ejemplo que debería funcionarte es:

setlocale(LC_TIME, 'es_ES.UTF-8');
echo strftime("%B", $firstDayOfMonth);

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.