Convert C # DateTime to Angular Date

I have an Angular collection related to a repeater that populates from MVC JsonResult.

$scope.loadData = function () { $http.get('/Product/GetDiscountCodes') .then(function (result) { console.log(result); $scope.discountCodes = result.data.DiscountCodes; $scope.selected = {}; }); }; 

One of the fields in the repeater is populated with a date. The date returned from the server is C # DateTime, which looks like this:

1/5/2015 12:02:00 AM

However, when it is bound to Angular, the following is displayed:

/ Date (1420434120000) /

How can I correctly display the date in a text box in the format mm / dd / yyyy?

I tried the ui-utils date format, but that didn't work.

I also tried to create my own directive that formats the date correctly, but when a save event occurs, the date is sent to the server-side method.

  function inputDate() { return { require: 'ngModel', link: function (scope, element, attrs, ngModelController) { ngModelController.$parsers.push(function (data) { if (data === null) { return null; } var d = moment(data).format('YYYY-MM-DD'); return d; }); ngModelController.$formatters.push(function (data) { if (data === null) { return null; } return moment(data).format('MM/DD/YYYY'); }); } } } angular.module('discountApp') .directive('inputDate', inputDate); 

Thanks for the help!

+6
source share
4 answers
 var app = angular.module('app',[]); app.filter('ctime', function(){ return function(jsonDate){ var date = new Date(parseInt(jsonDate.substr(6))); return date; }; }); app.controller('fCtrl', function($scope){ $scope.date = '/Date(1420875802707)/'; }); 
+8
source

use the command {sampledate.slice (6, -2) | date: 'dd / MM / YYYY'}

+7
source

This seems to be the problem with the serialization library that you use in .NET. Check out this Scott Hanselman blog post.

http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx

He talks about this very issue. The date should be serialized as the ISO 8601 .

You may need to change your serializer, see here Installing a standard JSON serializer in ASP.NET MVC

+2
source

using script code: $filter('date')($scope.Your_DateTime_Model, 'MM/dd/yyyy')

using code: <input class="form-control" type="text" data-ng-model="Your_DateTime_Model | date:'MM/dd/yyyy'" />

-1
source

Source: https://habr.com/ru/post/986264/


All Articles