Skip to content

Instantly share code, notes, and snippets.

@kwokhou
Last active March 1, 2016 08:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kwokhou/5873356 to your computer and use it in GitHub Desktop.
Save kwokhou/5873356 to your computer and use it in GitHub Desktop.
AngularJS filter to format ASP.NET JSON Date
// Format a /Date(XXXXXXXXXXXXXXXX)/ into a JSON date object.
angular.module('jsonDate', []).filter('jsonDate', function () {
return function (input, format) {
if (angular.isUndefined(input))
return;
// first 6 character is the date
var date = new Date(parseInt(input.substr(6)));
// default date format
if (angular.isUndefined(format))
format = "MM/DD/YYYY";
format = format.replace("DD", (date.getDate() < 10 ? '0' : '') + date.getDate()); // Pad with '0' if needed
format = format.replace("MM", (date.getMonth() < 9 ? '0' : '') + (date.getMonth() + 1)); // Months are zero-based
format = format.replace("YYYY", date.getFullYear());
return format;
};
});
@xyanide
Copy link

xyanide commented Nov 23, 2013

I found the above snippet a little bit too restrictive in the available formats and changed your snippet to the following.
This injects the $filter as a dependency and uses the AngularJS filter as the date formatter.

All this does now is take the date string and remove the first 6 characters and then pass it on to the AngularJS formatter.

angular.module('jsonDate', []).filter('jsonDate', function ($filter) {
    return function (input, format) {
        return $filter('date')(parseInt(input.substr(6)), format);
    };
});

@hoooknew
Copy link

Or you could just use a filter to convert the string to an int and use the built in date filter.

{{ MyDate | aspDate | date : 'shortDate' }}
angular.module('filters')
    .filter('aspDate', function () {
        'use strict';

        return function (input) {

            if (input) {
                return parseInt(input.substr(6));
            }
            else {
                return;
            }            
        };
    });

@hemantvikram
Copy link

Hi kwokhou,
Firebug shows error in the console window. Can you please verify and update

Thanks,
Hemant

@nmvuong92
Copy link

Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment