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

6

I have an object Date in my controller in Angular.

 $scope.date = new Date;

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

Is there any formatting to display this in angular?

    
asked by Wallace Maxters 07.11.2016 в 19:55
source

2 answers

7

Use the date filter.

By passing MMM as parameter, the output will be the name of the shortened month (Jan - Dec). Using MMMM the output will be the month name in full (January - December).

It is also possible to use the date direct filter on the controller, injecting $filter .

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

Complete 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><scriptsrc="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>
    
answered by 07.11.2016 / 20:01
source
0

If you want to use pure 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()));
    
answered by 07.11.2016 в 20:05