Create an AngularJS datefilter to properly display JSON date strings

Working with AngularJS often puts me in a situation where I need to deal with date strings in JSON returned from some .net server and looking like the following:

/Date(1297246301973)/

The string returned here represents the date in milliseconds and before you can use this date in your application, you need to convert it properly. Luckily, in AngularJS you can just create a custom filter like the following:

app.filter("dateFilter", function () {
    return function (item) {
        if (item != null) {
            return new Date(parseInt(item.substr(6)));
        }
        return "";
    };
});

You can then use the filter in the following way in your HTML:

    <tr ng-repeat="t in Result">
        <td>{{t.Date | dateFilter | date:"dd-MM-yyyy"}}</td>
    </tr>

You can see here that first I convert the JSON date string to a real date, and then I just use the regular date-filter in AngularJS in order to properly format it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s