Last active
March 1, 2016 08:33
-
-
Save kwokhou/5873356 to your computer and use it in GitHub Desktop.
AngularJS filter to format ASP.NET JSON Date
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}; | |
}); |
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;
}
};
});
Hi kwokhou,
Firebug shows error in the console window. Can you please verify and update
Thanks,
Hemant
Thank you very much!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.