Convert month number to name

Asked

Viewed 14,461 times

10

I need to convert the number of the month to the name of the same, but it has to be in Portuguese (and preferably without the need to substr)

I can do this with the standard English language

$monthNum  = 3;
$dateObj   = DateTime::createFromFormat('!m', $monthNum);
$monthName = $dateObj->format('F');
echo substr($monthName, 0, 3);
// output Mar

online test

There is a way to modify the language type to en-Br to use this function?


I don’t want to create a array() containing all the months already abbreviated and in Portuguese. I want a solution in-built

  • 2

    This might help, http://answall.com/questions/8317/como-fazer-a-fun%C3%A7%C3%A3o-date-formatar-uma-data-em-portugu%C3%Aas

  • 5

    I’m sorry, this is the first time I’ve asked a question in this ER. If I did wrong, please put a comment so I can correct, only vote negatively does not help improve the question.

  • @lost maybe help, searched the site before creating the question and found nothing. I was looking for something directly related to the title I created.

6 answers

12


With the help of @lost comment where it indicates the question How to make the date() function format a date in English? i made the following modifications to access the date I need (note that the strtotime is a little different from the proposed in the question, but it’s what I need)

setlocale( LC_ALL, 'pt_BR', 'pt_BR.iso-8859-1', 'pt_BR.utf-8', 'portuguese' );
date_default_timezone_set( 'America/Sao_Paulo' );

echo strftime('%h', strtotime("-3 months"));

Online test

7

Although there is already an answer, it is the caveat that regarding the location, the class Datetime is extended and does not pay attention to what has been defined, and it is necessary to use strftime()

In your case, to return the textual representation complete would look like this:

strftime( '%B', $dateObj -> getTimestamp() );

I highlighted the term complete because you wear a replace() to shorten the output. In this case, it would be more interesting to use:

strftime( '%b', $dateObj -> getTimestamp() );

And get the correct abbreviated representation.

  • +1 very good the point. It is very important that fact.

6

I know it’s been a while since you’ve been asked, and you have solutions based on locales, but as a second option, I’d like to put this approach as an example of a solution without logical testing.

I think it’s bad practice to cuddle if'It’s like there’s no tomorrow.

From this, you can assemble class, function, spindle, etc... The idea is to exemplify how to do the same thing, without using nested logic tests, or switch's huge.

    $numero_dia = date('w')*1;
    $dia_mes = date('d');
    $numero_mes = date('m')*1;
    $ano = date('Y');
    $dia = array('Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado');
    $mes = array('', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro');
    echo $dia[$numero_dia] . ", " .$dia_mes . " de " . $mes[$numero_mes] . " de " . $ano . ".";

Check-out: Friday, September 25, 2014.

4

The answers already present are the way forward, but for those with problems defining the locale for English, sometimes impossible or limited scenario due to server definitions, a function is based on the definitions provided by setlocale, doing a check of the received values and returning the English-formatted date:

Function in PHP

/**
 * Converter TimeStamp para data em Português
 *
 * @param integer $timestamp Unix timestamp
 * @param boolean $hours Se "true" devolve também as horas
 * @param string $timeZone Zona a utilizar para gerar as horas
 *
 * @return string
 */
function dataEmPortugues ($timestamp, $hours = FALSE, $timeZone = "Europe/Lisbon") {

    $dia_num = date("w", $timestamp);// Dia da semana.

    if($dia_num == 0){
    $dia_nome = "Domingo";
    }elseif($dia_num == 1){
    $dia_nome = "Segunda";
    }elseif($dia_num == 2){
    $dia_nome = "Terça";
    }elseif($dia_num == 3){
    $dia_nome = "Quarta";
    }elseif($dia_num == 4){
    $dia_nome = "Quinta";
    }elseif($dia_num == 5){
    $dia_nome = "Sexta";
    }else{
    $dia_nome = "Sábado";
    }

    $dia_mes = date("d", $timestamp);// Dia do mês

    $mes_num = date("m", $timestamp);// Nome do mês

    if($mes_num == 01){
    $mes_nome = "Janeiro";
    }elseif($mes_num == 02){
    $mes_nome = "Fevereiro";
    }elseif($mes_num == 03){
    $mes_nome = "Março";
    }elseif($mes_num == 04){
    $mes_nome = "Abril";
    }elseif($mes_num == 05){
    $mes_nome = "Maio";
    }elseif($mes_num == 06){
    $mes_nome = "Junho";
    }elseif($mes_num == 07){
    $mes_nome = "Julho";
    }elseif($mes_num == 08){
    $mes_nome = "Agosto";
    }elseif($mes_num == 09){
    $mes_nome = "Setembro";
    }elseif($mes_num == 10){
    $mes_nome = "Outubro";
    }elseif($mes_num == 11){
    $mes_nome = "Novembro";
    }else{
    $mes_nome = "Dezembro";
    }
    $ano = date("Y", $timestamp);// Ano

    date_default_timezone_set($timeZone); // Set time-zone
    $hora = date ("H:i", $timestamp);

    if ($hours) {
        return $dia_nome.", ".$dia_mes." de ".$mes_nome." de ".$ano." - ".$hora;
    }
    else {
        return $dia_nome.", ".$dia_mes." de ".$mes_nome." de ".$ano;
    }
}

Example of use:

// data actual
echo dataEmPortugues(time());

// uma outra data
echo dataEmPortugues(strtotime("2014-07-17 21:49:23"));

// com data e hora
echo dataEmPortugues(strtotime("2014-07-17 21:49:23"), TRUE);

// com data e hora São Paulo
echo dataEmPortugues(strtotime("2014-07-17 21:49:23"), TRUE, "America/Sao_Paulo");

Example Result

View Online Example - PHP Sandbox

// data actual
// Terça, 17 de Junho de 2014

// uma outra data
// Quinta, 17 de Julho de 2014

// com data e hora
// Quinta, 17 de Julho de 2014 - 21:49

// com data e hora São Paulo
// Quinta, 17 de Julho de 2014 - 17:49
  • Tip, Swap the set of elseif for switch. performance is better and is easier to read.

1

I believe you want something well summarized and simple just the same basic.

Discover the Month

<form action="" method="POST"> <!--passando os parametros pelo metodo post-->
    <fieldset>
        <legend><H3>INSIRA UM NÚMERO DE 1 A 12 </H3></legend>
        <p>
            <b>MÊS:</b> <input type="text" name="pos" required><!--armazena a opção na váriavel pos -->
        </p>

        <input type="submit" name="identifica" value="Qual é o Mês ?"><!--Identificando o fomulario  no neame para mandar para o php-->

        <?php

            if (isset($_POST['identifica'])) {  /* validando os campos se estão preechidos pelo isset que retorna true e recebe os paramentros 
                do formulario pelo identifica e seu respectivo método post*/
            }   

            $pos = intval($_POST["pos"]);   //declarando a váriavel pos erecebendo o valor inteiro pelo intval

            if (($pos >= 13)||($pos <=0)){// validando se o usuário digitou valores válidos
                echo "<br><br><b>Não digite letras!<br>E valores somente de 1 a 12.</b>";

            }else{

                $mes = array("","Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto",
                "Setembro","Outubro","Novembro","Dezembro");

                    echo "<br><br><b>Você escolheu ".$mes[$pos]."</b>";// retornando o mes do ano no array de acordo com a posição que foi inserida no formulário 
                    // e armazenada na váriavel $pos
            }

        ?>
        <!--fim do programa-->
    </fieldset>
</form>

1

There is another way. Your server needs to support setting up the pt_BR locale:

$monthNum  = 3;
$dateObj   = DateTime::createFromFormat('m', $monthNum);
$dateObj->setTimezone(new DateTimeZone('America/Sao_Paulo'));
$monthName = $dateObj->format('M');
echo $monthName;

See working

Browser other questions tagged

You are not signed in. Login or sign up in order to post.