Correctly format ASP.NET MVC dates for AngularJS

前端 未结 4 1532
灰色年华
灰色年华 2021-01-05 23:51

I am using AngularJS to get data from an ASP.NET server application and display it on the client side. Here is what I\'m getting:



        
相关标签:
4条回答
  • 2021-01-06 00:14

    You should probably have a look at

    http://docs.angularjs.org/api/ng.filter:date

    It gives you all the necessary tools to modify and display Date in the format you want.

    EDIT :

    Could you modify your server to not send the date as Date(****) but just the **** is fine... If you send the date as Date(****), then you are left with 2 options both of which arent good.

    1. TO eval the Date. NO eval.. its not good for your health.
    2. Strip out the Date using a combination of regex.. Again, its possible.. but not recommended.

    why send it in and strip it out? Why not just take it out of the server side itself?

    0 讨论(0)
  • 2021-01-06 00:25

    The quick fix

    If changing the format in MVC isn't an option, you can do this:

    {{ team.CreatedOn.slice(6, -2) | date: 'yyyy-MM-dd HH:mm:ss' }}
    

    The key bit is .slice(6, -2)—it trims off all the extra junk leaving you with just the epoch time.


    Want a filter?

    If you use this a lot, you may prefer a custom filter. This one wraps the existing date filter:

    .filter('mvcDate', ['$filter', $filter =>
      (date, format, timezone) =>
        date && $filter('date')(date.slice(6, -2), format, timezone)
    ]);
    

    Now just replace the date filter with our custom one:

    {{ team.CreatedOn | mvcDate: 'yyyy-MM-dd HH:mm:ss' }}
    

    Here's a working example on JSFiddle.

    0 讨论(0)
  • 2021-01-06 00:29

    Create custom filter as below:

    app.filter("dateFilter", function () {
        return function (item) {
            if (item != null) {
                return new Date(parseInt(item.substr(6)));
            }
            return "";
        };
    });
    

    You can then apply the filter in your HTML

    <tr ng-repeat="team in teams" class="thumbnail">
    <td>{{team.CreatedOn | dateFilter | date:"dd-MM-yyyy"}}</td>
    

    Hope it helps.

    0 讨论(0)
  • 2021-01-06 00:30

    In your ASP.NET MVC domain model have an extra property that renders the format expected by angular.

     public string CreatedOnJson
             {
                 get
                 {
                     return JsonConvert.SerializeObject(CreatedOn, new JavaScriptDateTimeConverter()).Replace("new Date(","").Replace(")","");
    
                 }
             }
    

    That way you can the use the angular date filter do display in way you prefer:

     {{team.CreatedOn | date:'yyyy-MM' }}
    
    0 讨论(0)
提交回复
热议问题