11

This seems like it should be simple but it has eluded me. I would like to convert my date string to a date object and filter how it is displayed.

I have a simple angular app and controller

myApp.controller('myAppCtrl', function($scope) {
   $scope.MyDate = Date("2014-09-23T15:26:49.1513672Z");
})

I have JSON returned from the server and the date I am working with is a string in the above format

from the angular documentation about date filters

  <span>{{1288323623006 | date:'medium'}}</span><br>

this works and the out put is: Oct 28, 2010 8:40:23 PM

When I try to use the filter on $scope.MyDate as follows:

  {{MyDate | date:'medium'}}

the date is not formatted but looks like this: Wed Sep 24 2014 07:40:02 GMT-0700 (Pacific Daylight Time)

Ultimately I would like to bind an input text box to this value and filter it like this:

<input type="text" class="form-control" ng-model="MyDatee | date:'medium'"/>

I am hoping once i get the simple version working I can get my actual problem solved with the text input.

Here is a plunker with the above code

user3648646
  • 711
  • 2
  • 15
  • 24

4 Answers4

15

For the first part, use new Date() instead:

$scope.MyDate = new Date("2014-09-23T15:26:49.1513672Z");

Second, you can create a directive to format the model in the input (modified from here)

The markup is like:

<input type="text" class="form-control" ng-model="MyDate" formatted-date format="medium" />

And the directive is like:

angular.module('myApp').directive('formattedDate', function(dateFilter) {
  return {
    require: 'ngModel',
    scope: {
      format: "="
    },
    link: function(scope, element, attrs, ngModelController) {
      ngModelController.$parsers.push(function(data) {
        //convert data from view format to model format
        return dateFilter(data, scope.format); //converted
      });

      ngModelController.$formatters.push(function(data) {
        //convert data from model format to view format
        return dateFilter(data, scope.format); //converted
      });
    }
  }
});

See updated plunkr

Community
  • 1
  • 1
Tom
  • 7,640
  • 1
  • 23
  • 47
4

in your $scope.MyDate please replace it with

$scope.MyDate = new Date("2014-09-23T15:26:49.1513672Z");
kdlcruz
  • 1,368
  • 13
  • 20
2

http://plnkr.co/edit/6Se6Cv6ozF0B7F0X6gjl?p=preview

but you can't use filter inside input to formate date inside input please see here

Using angularjs filter in input element

 $scope.MyDate = new Date("2014-09-23T15:26:49.1513672Z");
Community
  • 1
  • 1
sylwester
  • 16,498
  • 1
  • 25
  • 33
0

You can change the date format like this

<input type="text" class="form-control" value="{{MyDatee | date:'medium'}}"/>