2

when passing an object which contains a date from C# to AngularJS the value of the date appears as "/Date(1408482000000)/" and not as a valid date.

my angular code:

$scope.GetLastCompletedAction = function () {
       $http.post('Default.aspx/GetLastCompletedAction', {}).success(function (data,    status, headers, config) {
        $scope.objects = JSON.parse(data.d);
    }).error(function (data, status, headers, config) {
        $scope.status = status;
        console.log(status);
    });
}

objects is a list of objects. every object contains a field named startDate which appears invalid.

thanks, Nadav

Nadav
  • 2,589
  • 9
  • 44
  • 63
  • Did you try converting the date object in C# to timestamp? http://stackoverflow.com/questions/249760/how-to-convert-unix-timestamp-to-datetime-and-vice-versa and you can convert date back from the timestamp value to date in angular js http://stackoverflow.com/a/17925117/1904479 – Kailas Aug 21 '14 at 12:27
  • That *is* a valid JSON date format (one of several). What's going wrong? – Jon Skeet Aug 21 '14 at 12:28
  • Reffer to this https://docs.angularjs.org/api/ng/filter/date, – Nitin Chaurasia Aug 21 '14 at 12:35
  • i didn't try to convert the date object to timestamp, it is being converted (serialized) as a DateTime object. and when the date appears as "/Date(1408482000000)/" and i am trying to use inside a ng-repeat {{date | date : shortDate}} the operation doesn't work – Nadav Aug 21 '14 at 12:36

2 Answers2

1

you can use a funcion like this

$scope.formatDate = function (jsonDate)
{
    var milli = jsonDate.replace(/\/Date\((-?\d+)\)\//, '$1');
    var date = new Date(parseInt(milli));
    return date;
}
Sebastian Castaldi
  • 8,580
  • 3
  • 32
  • 24
0

I had this problem before and it is the Date object in javascript that does not consider that date valid.

If you pass to the Date constructor only the number which is inside /Date(*)/, you will see it will work. It did for me.

Hope I helped :)

AlexandruB
  • 678
  • 3
  • 15
  • I know about this solution but it isn't good enough for me, i need to be able to use the date inside a ng-repeat with angular. – Nadav Aug 21 '14 at 12:42
  • @NadavStern if you don't want to convert at server you can create custom filter and use angular date filter to format data inside the custom filter – charlietfl Aug 21 '14 at 12:47
  • When you do your post to `GetLastCompletedAction`, right after you parse, why don't you change all the dates objects and take only what is inside `/Date(*)/`? That way you can use it in angular and it is a valid `Date` object. – AlexandruB Aug 21 '14 at 12:51