Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js format date from json object

Tags:

My json response look like this:

[{"Id":"dab4580b-e24d-49f8-9fd5-2e968b10d3b5","Title":"MVVM-Sidekick 入精","CreatedOn":"\/Date(1390272893353)\/","IsChecked":false},{"Id":"66a0f134-e240-4cc4-96fa-ac3807853ca7","Title":"Windows Phone 开发入精","CreatedOn":"\/Date(1390018447080)\/","IsChecked":false}] 

the "CreatedOn" date is in this kind of format: '/Date(1390272893353)/'

when I bind this result to html table, the date cannot be formatted:

<td>{{item.CreatedOn | date: 'yyyy-MM-dd HH:mm'}}</td> 

still gives me:

/Date(1390272893353)/

I don't want to change any code on the server side (don't modify the json string), what's the best way to format this date?

like image 675
Edi Wang Avatar asked Mar 16 '14 09:03

Edi Wang


People also ask

How to convert JSON date to date format in Angular?

You need to convert it manually. As follows: new Date("1986-05-04T22:59:59.000Z"); Converting JSON object into a Javascript object can help you to achieve what you need.

How are dates represented in JSON?

To represent dates in JavaScript, JSON uses ISO 8601 string format to encode dates as a string. Dates are encoded as ISO 8601 strings and then treated just like a regular string when the JSON is serialized and deserialized.

Does JSON have a date?

JSON format does not have a special type for dates. So dates have to be represented in JSONs as numbers of milliseconds or as strings.


1 Answers

I actually combined the answers from @Charminbear and @Nikos ending up in this filter which works quite nice and is quite clear without the regex:

myApp.filter("jsDate", function () {     return function (x) {         return new Date(parseInt(x.substr(6)));     }; }); 

This makes it possible to write

{{ $scope.item.CreatedOn | jsDate | date:"yyyy-MM-dd" }} 
like image 181
Tech Avatar answered Sep 18 '22 07:09

Tech