2

<input type="text" ng-model="user.User.DateOfBirth"> is in my view. user.User.DateOfBirth is currently in YYYYMMDD format, but I want it to show as mm/dd/yyyy format in the view. Is it possible to convert this just for the display?

2
  • 2
    Use a custom filter. {{user.User.DateOfBirth | date[:format]}} Commented Nov 15, 2013 at 15:20
  • well detailed method here stackoverflow.com/questions/14474555/… Commented Nov 15, 2013 at 15:58

2 Answers 2

4

This also may help you

http://jsfiddle.net/mikeeconroy/Hu9m2/1/

.filter('myFormatDateFilter',function(){
    return function(input){
        if(angular.isDefined(input)){
           if(input.length >= 8){
                input = input.slice(0,8);

                input = input.slice(4,6) + '/' + input.slice(6,8) + '/' + input.slice(0,4);
            }
        }
        return input;
    };
});
Sign up to request clarification or add additional context in comments.

Comments

1

For outputting the data in the correct format try filters (in your case the date filter: http://docs.angularjs.org/api/ng.filter:date)

Well, for inputs that's another case. I guess you could always bind that input to another property, watch that and parse it yourself and then assign it to your real model...

Some more insight, you could try something like this:

HTML:

<input type="text" ng-model="myDateInput">

In your JS controller use the following:

$scope.$watch('myDateInput', function (newValue) {
    $scope.user.User.DateOfBirth = $filter('date')(newValue, 'yyyy-MM-dd'); // Or whatever format your real model should use
});

$scope.$watch('user.User.DateOfBirth', function (newValue) {
    $scope.myDateInput = $filter('date')(newValue, 'yyyy-MM-dd'); // Or whatever format your input should use
});

It would probably be better though to force the user to use a certain input format, either by some sort of pattern matching (and therefore validation) or by some sort of special date input/widget.

6 Comments

My user.User.DateOfBirth isn't a valid JS date object
It doesn't have to be an object, it can be a string: taken from the Angular date filter docs: Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats
I get: Expression 'user.User.DateOfBirth | date: 'medium'' is non-assignable. Element: <input ng-model="user.User.DateOfBirth | date: 'medium'" type="text">
don't put the filter in your ng-model directive
then how do i do it in an input box?
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.