Search code examples
angularjsangular-filters

Angularjs: How to filter the date


I want to format it to date format like

dd-MM-yyyy

The data iam getting from API is as follows

 Mon Feb 13 2017 12:30:28 GMT+0000 (UTC)

Any help?


Solution

  • You can convert it in View or also in controller,

    1) Formatting the Date in the View:

    <p>Date Formatted in view = {{ today | date:"dd-MM-y" }}</p>

    {{ today | date:"dd-MM-y" }} is the default date filter of angular.

    2) Formatting the Date in the Controller:

    $scope.date = $filter('date')($scope.today, "dd-MM-yyyy");, where you need to inject the $filter module of angular.

    <!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <body>
    
    <div ng-app="myApp" ng-controller="datCtrl">
    
    <p>Date Formatted in view = {{ today | date:"dd-MM-y" }}</p>
    
    <p>Date Formatted in Controller = {{date}}</p>
    
    </div>
    
    <script>
    var app = angular.module('myApp', []);
    app.controller('datCtrl', function($scope,$filter) {
        $scope.today = new Date();
        $scope.date = $filter('date')($scope.today, "dd-MM-yyyy"); 
    });
    </script>
    
    <p>The date filter formats a date object to a readable format.</p>
    
    </body>
    </html>

    PLEASE RUN THE ABOVE SNIPPET

    Here is a working DEMO