Search code examples
angularjsdatetimeangularjs-ng-repeat

formatting date in angularJS table


I am creating a web app in angularJS I have a date in the following format

"response.data[0].Date = "/Date(1539887400000)/"

I can convert this date into normal MM-DD-YYYY with moment, like this

moment(response.data[0].Date).format('DD-MM-YYYY');

but while binding the data into table with ng-repeat I am not able to achieve this

I did something like this

<td>{{d.Date| date:'DD-MM-YYYY' }}</td>

but in table it still showing like /Date(1539887400000)/

what I need to do to convert /Date(1539887400000)/ into DD-MM-YYYY


Solution

  • Your issue is because the date filter you are using is an AngularJS defined one, and is designed to work on date objects, the number of seconds since the epoch, or specifically formatted strings (see: https://docs.angularjs.org/api/ng/filter/date). In your case, you are passing in a string "Date(1539887400000)", which doesn't adhere to any of specific formats that the date argument of the filter expects. Here are a few ways I would think about solving this:

    • You could initialize the date option after you have fetched the data from the database. An example would be: $scope.testDate = new Date(1539887400000);. You can then use the regular angular date filter on this object: {{testDate | date: 'dd-MM-yyyy'}}.
    • You can use angular-moment (link: https://github.com/urish/angular-moment), which has more features than the regular angularJS date filter. You can then use the amDateFormat and pass your string in, like so: {{d.Date | amDateFormat: 'DD-MM-YYYY'}}
    • You could parse out the number from the string that you currently have. Since the regular angularJS date filter can accept a number (seconds since epoch) as it's argument, it will properly format it.

    See an example plunker here showing some of these in action: https://plnkr.co/edit/quCvL3GhSux8ctYQqAwA