How to add Days through AngularJS Date Filter?

前端 未结 2 1842
轻奢々
轻奢々 2021-01-20 06:08

I have this code:


  

Empty Angular App

{{\"2015-07-08T15:10:
相关标签:
2条回答
  • 2021-01-20 06:19

    You could create a custom filter to convert the date from the format ISO8601 and add X days:

    myApp.filter('kDateAddFromDateISO8601', [function() {
      return function(isoDateString, days) {
    
        var parts;
        var isoTime;
        var date;
    
        isoDateString = isoDateString || "";
        days = days || 0;
    
        parts = isoDateString.match(/\d+/g);
        isoTime = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
        date = new Date(isoTime);
    
        if (days) {
          date.setDate(date.getDate() + days);
        }
    
        return date;
      };
    }]);
    

    And then you can use the filter:

    <div>{{"2015-07-08T15:10:10.530Z" | kDateAddFromDateISO8601 : 46 | date:'medium'}}</div>
    

    Output:

    Aug 23, 2015 12:10:10 PM

    Check the demo fiddle

    0 讨论(0)
  • 2021-01-20 06:26

    As you told, use javascript is better option.

    var app = angular.module('my-app', []);
    
    app.controller("my-controller", function($scope) {
      $scope.name = "world";
      $scope.mydate = new Date("2015-07-08T15:10:10.530Z");
    
      var numberOfDaysToAdd = 46;
      $scope.newdate = $scope.mydate.setDate($scope.mydate.getDate() + numberOfDaysToAdd); 
    
    });
    

    http://codepen.io/anon/pen/MwVNpq

    0 讨论(0)
提交回复
热议问题