<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?
Asked
Active
Viewed 1.4k times
2

Shamoon
- 41,293
- 91
- 306
- 570
-
2Use a custom filter. `{{user.User.DateOfBirth | date[:format]}}` – m.e.conroy Nov 15 '13 at 15:20
-
well detailed method here http://stackoverflow.com/questions/14474555/how-to-format-a-date-using-ng-model – charlietfl Nov 15 '13 at 15:58
2 Answers
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;
};
});

m.e.conroy
- 3,508
- 25
- 27
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.

eXaminator
- 353
- 1
- 8
-
-
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` – m.e.conroy Nov 15 '13 at 15:23
-
I get: `Expression 'user.User.DateOfBirth | date: 'medium'' is non-assignable. Element: ` – Shamoon Nov 15 '13 at 15:25
-
-
-
I added some code, I haven't tested it though, but it might work. Or just use it as inspiration ;) – eXaminator Nov 15 '13 at 16:06