161

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" />
Kailas
  • 7,350
  • 3
  • 47
  • 63
user16
  • 1,649
  • 2
  • 11
  • 6
  • 1
    Have you tried removing `ui-date-format="mm/dd/yyyy"` altogether? It looks like the default behavior without this option is what you want. – Lukas Mar 13 '14 at 23:22
  • Have you tried moment.js ? – Jscti Mar 13 '14 at 23:27
  • No I haven't tried moment.js. My server returns me Json string 20140313T00:00:00. I tried both way html5 input type date and ui-date-format. Removing ui-date-format says it's a string give it a format. – user16 Mar 13 '14 at 23:31
  • Using `$formatters` and `$parsers` per [this answer](http://stackoverflow.com/a/15346236/20712) solved my similar problem. – Ross Rogers Oct 13 '14 at 17:51
  • you can use filters in html as well as from javascript too, please refer : http://stackoverflow.com/a/27615392/1904479 – Kailas Apr 13 '16 at 09:39

15 Answers15

218

Angular.js has a built-in date filter.

demo

// in your controller:
$scope.date = '20140313T00:00:00';

// in your view, date property, filtered with date filter and format 'MM/dd/yyyy'
<p ng-bind="date | date:'MM/dd/yyyy'"></p>

// produces
03/13/2014

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/

Joseph Yaduvanshi
  • 20,241
  • 5
  • 61
  • 69
  • 2
    server returns me '20140313T00:00:00 and i want to show in mm/dd/yyyy format in an input like this -- – user16 Mar 14 '14 at 16:22
  • I'm not sure why my answer was downvoted. This answer is taken almost verbatim from Angular's docs. The mention of jQueryUI datepicker format strings is because the module being used in the question is ui-date which has a dependency on jQuery and jQueryUI. There's nothing incorrect or misleading in the answer. – Joseph Yaduvanshi May 04 '15 at 13:01
  • I don't think the jQuery UI link is correct for format strings. https://docs.angularjs.org/api/ng/filter/date appears to be more accurate. – TrueWill Sep 10 '15 at 18:50
  • @TrueWill OP is specifically asking about ui-date, which uses jQuery datepicker. The first link in my post links to the source code which has the format strings supported by angular. – Joseph Yaduvanshi Sep 10 '15 at 19:29
  • @JimSchubert this is my date string '2013-11-11 00:00:00' and it will not convert | date:'longdate', any suggestions? – alphapilgrim Feb 10 '16 at 23:28
  • @alphapilgrim You need to specify the correct format. 'longdate' is 'MMMM d, y', which doesn't match your string. Check out the comments in the source or angular docs and build the correct format string (https://github.com/angular/angular.js/blob/dc57fe97e1be245fa08f25143302ee9dd850c5c9/src/ng/filter/filters.js#L310). – Joseph Yaduvanshi Feb 11 '16 at 02:34
  • My date is comming like this DateTime : "2017/12/15" but doing this {{M.DateTime | date : 'dd-MM-yyyy'}} not changing date format. – Vishal Singh Feb 23 '16 at 05:36
  • using `ng-bind="foo" | date:'medium'` gives a handy little formatting, with an output such as: `Jan 23, 2017 10:10:58 PM`. This use of `"medium"` is outlined in the docs and I thought pretty cool and quick! – twknab Jan 24 '17 at 10:45
  • Seems like, if you have a Datetime value (i.e. "2017-05-12 18:48:13") the filter won't apply unless you do a REPLACE(date, ' ', 'T') in your SQL Select (to get "2017-05-12T18:48:13"). – Oliver N. May 18 '17 at 13:29
  • @OliverN. You're going to have a lot of issues with timezones if you do a string replace like this. Just parse the date in javascript and bind directly. e.g. `new Date(Date.parse("2017-05-12 18:48:13"))`. See http://plnkr.co/edit/HFFdXf2L5kINtNRPO6tv – Joseph Yaduvanshi May 18 '17 at 13:52
  • @JimSchubert Your own example returns "Invalid Date" when not adding the "T" between date and time. And that is the raw datetime value I get out of my European MySQL database. If you know a better workaround please let me know, but that was exactly my point. – Oliver N. May 19 '17 at 11:11
  • @OliverN. http://imgur.com/a/W8x6v It sounds like your issue is with your browser locale. `new Date`, creates localized date and most European browser settings are day-month-year rather than month-day-year. If you're querying in non-European format, your browser is trying to convert to a European format. My suggestion would be to extract a date encoded with timezone (the T, for example), directly supported by MySQL but your server code needs to serialize for your client correctly. Or, you could expose a 64-bit integer plus timezone and convert client side. Be warned, browser JS is 52-bits. – Joseph Yaduvanshi May 19 '17 at 13:43
  • Specifically, I'd convert to UTC: `DATE_FORMAT( CONVERT_TZ(timestamp_here, @@session.time_zone, '+00:00') ,'%Y-%m-%dT%TZ')` You can try the plunker I linked above with the format from this query to see if it works in your browser: `2017-05-12T18:48:13Z` Just be sure you're not removing that encoded timezone in server code. Search for ISO 8601 (the timezone embedded format). – Joseph Yaduvanshi May 19 '17 at 13:59
104

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:

<label ng-bind="formatDate(date) |  date:'MM/dd/yyyy'"></label>

and in the js file use:

    // @Function
    // Description  : Triggered while displaying expiry date
    $scope.formatDate = function(date){
          var dateOut = new Date(date);
          return dateOut;
    };

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:

$scope.eqpCustFields[i].Value = $filter('date')(new Date(dateValue),'yyyy-MM-dd');

that is in case you already have a date with you, else you can use the following code to get the current system date:

$scope.eqpCustFields[i].Value = $filter('date')(new Date(),'yyyy-MM-dd');

For more details on date Formats, refer : https://docs.angularjs.org/api/ng/filter/date

Kailas
  • 7,350
  • 3
  • 47
  • 63
30

I am using this and it is working fine.

{{1288323623006 | date:'medium'}}: Oct 29, 2010 9:10:23 AM
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}: 2010-10-29 09:10:23 +0530
{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}: 10/29/2010 @ 9:10AM
{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}: 10/29/2010 at 9:10AM
Vinayak Garg
  • 6,518
  • 10
  • 53
  • 80
Ravindra Kumar
  • 1,842
  • 14
  • 23
  • this does not work for me, if I pass a JS Date object. any suggestions why? – Panshul Feb 17 '17 at 09:41
  • It should work only for the date formate where date is in milliseconds and in your case the date is in Date Formate. Follow: https://www.w3schools.com/js/js_date_formats.asp – Ravindra Kumar Mar 09 '17 at 10:57
19

This isn't really exactly what you are asking for - but you could try creating a date input field in html something like:

<input type="date" ng-model="myDate" />

Then to print this on the page you would use:

<span ng-bind="convertToDate(myDate) | date:'medium'"></span>

Finally, in my controller I declared a method that creates a date from the input value (which in chrome is apparently parsed 1 day off):

$scope.convertToDate = function (stringDate){
  var dateOut = new Date(stringDate);
  dateOut.setDate(dateOut.getDate() + 1);
  return dateOut;
};

So there you have it. To see the whole thing working see the following plunker: http://plnkr.co/edit/8MVoXNaIDW59kQnfpaWW?p=preview .Best of luck!

drew_w
  • 10,320
  • 4
  • 28
  • 49
11

This will work:

{{ oD.OrderDate.replace('/Date(','').replace(')/','') | date:"MM/dd/yyyy" }}

NOTE: once you replace these then remaining date/millis will be converted to given foramt.

shilovk
  • 11,718
  • 17
  • 75
  • 74
Nitish Kumar
  • 111
  • 1
  • 2
11

I use filter

.filter('toDate', function() {
  return function(items) {
    return new Date(items);
  };
});

then

{{'2018-05-06 09:04:13' | toDate | date:'dd/MM/yyyy hh:mm'}}
10

see angular date api : AngularJS API: date


The Angular - date filter:

Usage:

{{ date_expression | date  [: 'format']  [: 'timezone' ] }}


Exampe:

Code:

 <span>{{ '1288323623006' | date:'MM/dd/yyyy' }}</span>

Result:

10/29/2010
Eddy
  • 3,623
  • 37
  • 44
4

Just pass UTC date format from your server side code to client side

and use below syntax -

 {{dateUTCField  +'Z' | date : 'mm/dd/yyyy'}}

 e.g. dateUTCField = '2018-01-09T10:02:32.273' then it display like 01/09/2018
1

After looking at all the above solutions, the following was the quickest solution for me. If you are using angular-material:

 <md-datepicker ng-model="member.reg_date" md-placeholder="Enter date"></md-datepicker>

To set the format:

app.config(function($mdDateLocaleProvider) {
    $mdDateLocaleProvider.formatDate = function(date) {
        // Requires Moment.js OR enter your own formatting code here....
        return moment(date).format('DD-MM-YYYY');
    };
});

Edit: You also need to set the parseDate for typing in a date (from this answer Change format of md-datepicker in Angular Material)

$mdDateLocaleProvider.parseDate = function(dateString) {
    var m = moment(dateString, 'DD/MM/YYYY', true);
    return m.isValid() ? m.toDate() : new Date(NaN);
};
Community
  • 1
  • 1
johan
  • 998
  • 6
  • 20
1
var app=angular.module('myApp',[]);
        app.controller('myController',function($scope){         
              $scope.names = ['1288323623006','1388323623006'];

        });

Here Controller name is "myController" and app name is "myApp".

<div ng-app="myApp" ng-controller="myController">
        <ul>
            <li ng-repeat="x in names">
                {{x | date:'mm-dd-yyyy'}}

            </li>

        </ul>
    </div>

Result will look like this :- * 10-29-2010 * 01-03-2013

Gopakumar
  • 187
  • 1
  • 8
1
{{convertToDate  | date :  dateformat}}                                             
$rootScope.dateFormat = 'MM/dd/yyyy';
geisterfurz007
  • 5,292
  • 5
  • 33
  • 54
  • 1
    Why you post comment with the same line as in your answer? And your answer is only some code, no explanation at all. – Pochmurnik Jul 26 '19 at 10:33
0

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 property dateFormat with the value from ng-date-format as you could espect.

Anyway the directive has a constant called uiDateConfig to add properties to opts.

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.

<input ui-date="dateOptions" ui-date-format="mm/dd/yyyy" ng-model="valueofdate" />

myAppModule.controller('MyController', function($scope) {
    $scope.dateOptions = {
        dateFormat: "dd-M-yy"
    };
});

The hardcoded solution:

If you don't want to repeat this procedure all the time change the value of uiDateConfig in date.js to:

.constant('uiDateConfig', { dateFormat: "dd-M-yy" })
borracciaBlu
  • 4,017
  • 3
  • 33
  • 41
0

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:

$valueofdate = date('Y-n-j',strtotime('theStringFromQuery'));

This will pass a String, for example: '1999-3-3' and JavaScript will do the parsing to an object with right format with

$scope.valueofdate = new Date(valueofdate);

<input ui-date ui-date-format="mm/dd/yyyy" ng-model="valueofdate" />
<input type="date" ng-model="valueofdate" />

Link to PHP for date formats: http://www.w3schools.com/php/func_date_date_format.asp.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
0

ng-bind="reviewData.dateValue.replace('/Date(','').replace(')/','') | date:'MM/dd/yyyy'"

Use this should work well. :) The reviewData and dateValue fields can be changes as per your parameter rest can be left same

Jayant Rajwani
  • 727
  • 9
  • 16
-1
// $scope.dateField="value" in ctrl
<div ng-bind="dateField | date:'MM/dd/yyyy'"></div>
Undo
  • 25,519
  • 37
  • 106
  • 129
Siddhartha
  • 1,473
  • 14
  • 10