I am using AngularJS to get data from an ASP.NET server application and display it on the client side. Here is what I'm getting:
ProjectID │ CreatedOn
══════════╪══════════════════════
13241 │ /Date(1338364250000)/
13411 │ /Date(1338370907000)/
As you can see, the date is not being displayed correctly. I want to format the date as YYYY-MM-DD HH:MM:SS
. How can I do this?
The HTML view:
<div ng-app ng-controller="FirstCtrl">
<table>
<thead>
<tr>
<td>
ProjectID
</td>
<td>
CreatedOn
</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="team in teams" class="thumbnail">
<td>
{{team.ProjectID}}
</td>
<td>
{{team.CreatedOn}}
</td>
</tr>
</tbody>
</table>
</div>
The action method:
public JsonResult GetUser()
{
return Json(new { data = ProjectService.GetPrefixUsedCount(1).ToArray() });
}
The JSON result returned:
{"data":[{"ProjectID":13241,"CreatedOn":"\/Date(1338364250000)\/"},
{"ProjectID":13411,"CreatedOn":"\/Date(1338370907000)\/"}]
If changing the format in MVC isn't an option, you can do this:
{{ team.CreatedOn.slice(6, -2) | date: 'yyyy-MM-dd HH:mm:ss' }}
The key bit is .slice(6, -2)
—it trims off all the extra junk leaving you with just the epoch time.
If you use this a lot, you may prefer a custom filter. This one wraps the existing date
filter:
.filter('mvcDate', ['$filter', $filter =>
(date, format, timezone) =>
date && $filter('date')(date.slice(6, -2), format, timezone)
]);
Now just replace the date
filter with our custom one:
{{ team.CreatedOn | mvcDate: 'yyyy-MM-dd HH:mm:ss' }}
Here's a working example on JSFiddle.
Create custom filter as below:
app.filter("dateFilter", function () {
return function (item) {
if (item != null) {
return new Date(parseInt(item.substr(6)));
}
return "";
};
});
You can then apply the filter in your HTML
<tr ng-repeat="team in teams" class="thumbnail">
<td>{{team.CreatedOn | dateFilter | date:"dd-MM-yyyy"}}</td>
Hope it helps.
You should probably have a look at
http://docs.angularjs.org/api/ng.filter:date
It gives you all the necessary tools to modify and display Date in the format you want.
EDIT :
Could you modify your server to not send the date as Date(****) but just the **** is fine... If you send the date as Date(****), then you are left with 2 options both of which arent good.
why send it in and strip it out? Why not just take it out of the server side itself?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With