AngularJS – convert dates in controller

AngularJS – convert dates in controller

Asked on December 19, 2018 in AngularJs.
Add Comment


  • 4 Answer(s)

    This is a great fast solution

    item.date = $filter('date')(item.date, "dd/MM/yyyy"); // for conversion to string
    

    We have to use ISO format yyyy-MM-dd , in the case of using HTML5 type=”date” .

    item.dateAsString = $filter('date')(item.date, "yyyy-MM-dd"); // for type="date" binding
     
    <input type="date" ng-model="item.dateAsString" value="{{ item.dateAsString }}" pattern="dd/MM/YYYY"/>
    

    Even this pattern=”” with type=”date” looks non-standard,in chrome-31 it is work good.

    Answered on December 19, 2018.
    Add Comment

    We can do it by following below procedure,

    First create a filter.js .this is used for reusable itself.

    angular.module('yourmodule').filter('date', function($filter)
    {
        return function(input)
        {
          if(input == null){ return ""; }
          var _date = $filter('date')(new Date(input), 'dd/MM/yyyy');
          return _date.toUpperCase();
        };
    });
    

    The vision of code,

    <span>{{ d.time | date }}</span>
    

    In the controller,

    var filterdatetime = $filter('date')( yourdate );
    

    Click this link for Date filtering and formatting in Angular js.

    Answered on December 19, 2018.
    Add Comment

    Use this code,

    var item=1387843200000;
    var date1=new Date(item);
    

    Here , the date1 is Date object.

    Answered on December 19, 2018.
    Add Comment
    app.controller("EditCtrl", [ "$scope", "$filter", "db" function ($scope, $filter, db){
    
        // this gets me an item object
        var item = db.readItem();
    
        // item date = 1387843200000
        // this returns undefined 
        item.date = $filter('date')(date[ item.date, "dd/MM/yyyy"]);
    
    }]);

    Edit.html – template

    <form name="editForm" class="form-validate">
    
            <div class="form-group">
                <label for="date">Event date.</label>
                <input type="date" class="form-control" ng-model="event.date" id="date" required />
            </div>
    
            <a href="#/" class="btn btn-danger ">Cancel</a>
            <button id="addEvent" class="btn btn-primary pull-right" ng-disabled="isClean() || editForm.$invalid" ng-click="saveEvent()">Save event.</button>
    
        </form>
    Answered on February 22, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.