How to format a date displaying the month name in angular?

Asked

Viewed 2,567 times

6

I have an object Date on my Angular controller.

 $scope.date = new Date;

I would like to format this date in the view to display the name of the month in full. I want the name to be displayed in English.

Is there any formatting to display this in angular?

2 answers

7


Use the filter date.

Passing by MMM as parameter, the output will be the shortened month name (Jan - Dec). Using MMMM the departure will be the month name in full (January - December).

It is also possible to use the filter date directly into the controller, injecting $filter.

In order for the names to be displayed in English, you will need to have the script internationalization referenced in the project.

Full example:

var app = angular.module('dt-app', []);

app.controller('testCtrl', function($scope, $filter){
  $scope.data = new Date();  
  $scope.dataFormatada = $filter('date')($scope.data, 'MMMM');
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-i18n/1.6.4/angular-locale_pt-br.min.js"></script>

<div ng-app="dt-app">
  <div ng-controller="testCtrl">
    <div>    
      <h4>Formatando direto na view</h4>
      {{ data | date: 'MMM'}}<br>
      {{ data | date: 'MMMM'}}
    </div>
    
    <hr>
    
    <div id="dt-ctrl">
      <h4>Formatando no controller:</h4>
      {{ dataFormatada }}
    </div>
  </div>
</div>

0

If you wish to use purely Javascript:

function formatarDataExtenso(data) {
  // Meses possíveis
  var meses = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
  // Dias possíveis
  var diasSemana = ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'];
  // Partes da data informada
  var dia = data.getDate();
  var dias = data.getDay();
  var mes = data.getMonth();
  var ano = data.getYear();
  // Resultado
  var extenso = '';

  // Para o navegador Netscape o ano começa em 1900
  if (navigator.appName == "Netscape") {
    ano = ano + 1900;
  }

  return extenso = diasSemana[dias] + ', ' + dia + ' de ' + meses[mes] + ' de ' + ano;
}

// Teste com a data atual
console.log(formatarDataExtenso(new Date()));

Browser other questions tagged

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