I want to format date as mm/dd/yyyy
. I tried the following and none of it works for me.
Can anyone help me with this?
reference: ui-date
<input ui-date ui-date-format="mm/dd/yyyy" ng-model="valueofdate" />
<input type="date" ng-model="valueofdate" />
Angular.js has a built-in date filter.
demo
You can see the supported date formats in the source for the date filter.
edit:
If you're trying to get the correct format in the datepicker (not clear if you're using datepicker or just trying to use it's formatter), those supported format strings are here: https://api.jqueryui.com/datepicker/
Ok the issue it seems to come from this line:
https://github.com/angular-ui/ui-date/blob/master/src/date.js#L106.
Actually this line it's the binding with jQuery UI which it should be the place to inject the data format.
As you can see in
var opts
there is no propertydateFormat
with the value from ng-date-format as you could espect.Anyway the directive has a constant called
uiDateConfig
to add properties toopts
.The flexible solution (recommended):
From here you can see you can insert some options injecting in the directive a controller variable with the jquery ui options.
The hardcoded solution:
If you don't want to repeat this procedure all the time change the value of
uiDateConfig
in date.js to:I had the same issue and as the above comments, thought there must be a native method in JavaScript. The thing is
new Date(valueofdate)
returns a Date object.But, check in http://www.w3schools.com/js/js_date_formats.asp, the part that says leading zero. A date from a String, for example an echo from PHP, must be like:
This will pass a String, for example:
'1999-3-3'
and JavaScript will do the parsing to an object with right format withLink to PHP for date formats: http://www.w3schools.com/php/func_date_date_format.asp.
If you are not having an input field, rather just want to display a string date with a proper formatting, you can simply go for:
and in the js file use:
This will convert the date in string to a new date object in javascript and will display the date in format MM/dd/yyyy.
Output: 12/15/2014
Edit
If you are using a string date of format "2014-12-19 20:00:00" string format (passed from a PHP backend), then you should modify the code to the one in: https://stackoverflow.com/a/27616348/1904479
Adding on further
From javascript you can set the code as:
that is in case you already have a date with you, else you can use the following code to get the current system date:
For more details on date Formats, refer : https://docs.angularjs.org/api/ng/filter/date
After looking at all the above solutions, the following was the quickest solution for me. If you are using angular-material:
To set the format:
Edit: You also need to set the parseDate for typing in a date (from this answer Change format of md-datepicker in Angular Material)
Here Controller name is "myController" and app name is "myApp".
Result will look like this :- * 10-29-2010 * 01-03-2013