Format AngularJS date

0

I'm taking a person's data from an API and I need to format a date.

When calling the API to get the date

vm.preconcedido.datosPersona.datosPersonales.fechaNacimiento

I see the date so that 1961-05-29T00: 00: 00.000 + 0100

I tried to format with the

.format(DD/mm/AAAA);

and I did not format the date correctly.

How could I format the date correctly?

Thank you very much, best regards

    
asked by derek 30.08.2018 в 11:27
source

2 answers

2

Natively AngularJS has the filter date , in the one that you only have to specify the desired format. Now, if you only want to use the native form of Javascript you should get day , month (this should be added to 1, since January counts as month 0) and year separately and concatenate them in a variable; and finally if you use momentjs only specify the format with the function format('formatoDeseado') .

I'll give you the examples

var app = angular.module('app', []);
app.controller('ctrl', ['$scope', function($scope){
  $scope.fecha1 = new Date();
  $scope.fecha2 = new Date().getDate() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getFullYear();
  $scope.fecha3 = moment().format('DD-MM-YYYY');
}])
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container" ng-app="app" ng-controller="ctrl">
  <label class="control-label text-success">Forma nativa AngularJS -> {{fecha1 | date: 'dd-MM-yyyy'}}</label>
  <br>
  <label class="control-label text-danger">Forma nativa Javascript -> {{fecha2}}</label>
  <br>
  <label class="control-label text-info">Forma momentJS -> {{fecha3}}</label>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
    
answered by 30.08.2018 / 15:21
source
0

A faster way to convert is to use JavaScript functions natively;

$scope.miFecha = new Date($scope.miFecha).toString()
$scope.miFecha = new Date($scope.miFecha).toString()
$scope.miFecha = new Date($scope.miFecha).toLocaleString()
$scope.miFecha = new Date($scope.miFecha).toLocaleDateString()
$scope.miFecha = new Date($scope.miFecha).toLocaleTimeString()

Or directly with the binding {{}}, You could do the following:

<div>
{{miFecha |date}}
{{miFecha |date : "dd.MM.y"}}
{{miFecha |date : "dd/MM/y" }}
{{miFecha |date : "dd-MM-y"}}
</div>

I'll give you an example: link

Also in your main module you can place the following configuration :

  $mdDateLocaleProvider.formatDate = function(date) {
            return date ? moment(date).format('DD/MM/YYYY') : '';
        };

        $mdDateLocaleProvider.parseDate = function(dateString) {
            var m = moment(dateString, 'DD/MM/YYYY', true);
            return m.isValid() ? m.toDate() : new Date(NaN);
        };
    
answered by 07.09.2018 в 21:55