AngularJS - convert dates in controller

ghz 1years ago ⋅ 5253 views

Question

Could anyone please suggest me how to convert date from this 1387843200000 format into this 24/12/2013 inside my controller?

Just FYI my dates are stored in this way & when binding to edit form with input type="date" field is not being populated at all.

#Plunker demo here.

EditCtrl

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>

Answer

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

http://docs.angularjs.org/api/ng.filter:date

But if you are using HTML5 type="date" then the ISO format yyyy-MM-dd MUST be used.

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"/>

http://www.w3.org/TR/html-markup/input.date.html

NOTE: use of pattern="" with type="date" looks non-standard, but it appears to work in the expected way in Chrome 31.