Formatting ASP.NET JSON Date Values in AngularJS
When working with ASP.NET backend services, JSON serialization often converts date objects into a specific format like /Date(1448864369815)/. While AngularJS provides built-in date formatting capabilities, handling this particular format requires some additional processing.
AngularJS offers two approaches to utilize its date filter: within expressions or programmatically in controllers.
Using Date Filters in Expressions
{{ timestampValue | date:'yyyy-MM-dd HH:mm:ss' }}
Using Date Filters in Controllers
// Inject $filter service into your controller
app.controller("dateController", ["$scope", "$filter", function($scope, $filter){
$scope.currentTime = new Date();
// Programmatically apply date formatting
$scope.formattedTime = $filter("date")($scope.currentTime, "yyyy-MM-dd HH:mm:ss");
}]);
Since the date filter accepts timestamp values, we can extract the numeric timestamp from the ASP.NET JSON date format and apply formatting:
// Output will be formatted as 2015-11-30 14:19:29
$scope.formattedTimestamp = $filter("date")(1448864369815, "yyyy-MM-dd HH:mm:ss");
Extracting Timestamps from ASP.NET JSON Dates
To extract the timestamp from the /Date(...)/ format, we can use the following approach:
var serverDate = "/Date(1448864369815)/"; // Convert to numeric timestamp var timestamp = Number(serverDate.replace(/\/Date\((\d+)\)\//, "$1"));
Creating a Custom Filter for ASP.NET JSON Dates
For more convenient handling, we can create a custom AngularJS filter that processes the ASP.NET JSON date format directly:
// Define custom filter aspNetDate
app.filter("aspNetDate", function($filter) {
return function(input, format) {
// Extract timestamp from ASP.NET JSON date format
var timestamp = Number(input.replace(/\/Date\((\d+)\)\//, "$1"));
// Apply date formatting
return $filter("date")(timestamp, format);
}
});
Once implemented, this custom filter can be used just like the built-in date filter:
Using the Custom Filter
// In controllers
$filter("aspNetDate")("/Date(1448864369815)/", "yyyy-MM-dd HH:mm:ss");
// In template expressions
{{"/Date(1448864369815)/" | aspNetDate:"yyyy-MM-dd HH:mm:ss"}}