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

0

4 Answers 4

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

1
  • This is great. Can there be an extension to validate the data as well?
    – Kangkan
    Commented Jul 7, 2016 at 17:11
4

in your $scope.MyDate please replace it with

$scope.MyDate = new Date("2014-09-23T15:26:49.1513672Z");
0
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");
0

You can change the date format like this

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.