How to format inital date value using AngularJS ui-date directive?
11,791
Your $scope.m.Dt property should be of date type, not string.
$scope.m =
{
name: "John",
Dt: new Date()
};
To set date format use ui-date-format directive, like:
<input title="Date" ui-date ui-date-format="mm-dd-yy" ng-model="m.Dt" />
See example in readme: https://github.com/angular-ui/ui-date#ui-date-format-directive
Related videos on Youtube
Author by
CHS
Updated on July 08, 2022Comments
-
CHS almost 2 years
When I get a model from the server it looks like this:
$scope.m = { name: "John", Dt: "2013-10-03T18:47:33.5049087-07:00" };
The view looks like:
<input title="Date" ui-date ng-model="m.Dt" />
I set the default date format on the jQuery datepicker to:
$.datepicker.setDefaults({dateFormat: 'mm-dd-yy'});
The initial value of the input stays "2013-10-03T18:47:33.5049087-07:00" though. It only formats as
mm-dd-yy
if I use the datepicker to change the date.How can I get the initial value to also be in
mm-dd-yy
format? -
CHS over 10 yearsYes, I'm aware it works with Date objects, but in a real world example your data comes from the server likely via JSON and your dates will not be objects, but strings. I can write a method to recurse thru the model and convert date strings to objects, but I was thinking for such a common scenario it would already be handled.
-
Alexander Puchkov over 10 yearsIt's not handled in angular, but you can create http interceptor with recursive method to convert date strings to objects as you mentioned. See this post for example: aboutcode.net/2013/07/27/json-date-parsing-angularjs.html