arun kataria
arun kataria

Reputation: 23

Convert date format from object containing dates in AngularJS

How to convert above all the date into YYYY-MM-DD format? I have used this way but it's not working.

$scope.dateDatas = [0:"29-09-2016", 1:"30-09-2016",2:"01-10-2016",3:"02-10-2016",4:"03-10-2016"]

angular.forEach ($scope.dateDatas, 
            function (value) {
            var d = $filter('date')(value, 'yyyy-mm-dd');
            console.log(d);
          });

Upvotes: 0

Views: 1148

Answers (1)

mrzli
mrzli

Reputation: 17379

How about this:

$scope.dateDatas = ["29-09-2016", "30-09-2016", "01-10-2016", "02-10-2016", "03-10-2016"];
$scope.result = [];

angular.forEach ($scope.dateDatas, function (value) {
    var splitValue = value.split("-");
    var date = new Date(splitValue[2], splitValue[1] - 1, splitValue[0]);

    var res = $filter('date')(date, 'yyyy-MM-dd');
    $scope.result.push(res);
    console.log(res);
});

Here are the issues:

  1. On the first line, the there shouldn't be any pairs in an array, remove the 'key', and keep the value:

    $scope.dateDatas = ["29-09-2016", "30-09-2016", "01-10-2016", "02-10-2016", "03-10-2016"];

  2. As a side note, remember also to put semicolon after the array.

  3. $filter('date') will work on dates, not on strings. You first need to convert your initial string to a date object. I got the code to convert this string to Date from here. Also note that you need to decrease the month value by 1 before passing it to Date constructor because month in Date constructor is 0-based for some reason (expects 0 for January, 1 for February etc):

    var splitValue = value.split("-");
    var date = new Date(splitValue[2], splitValue[1] - 1, splitValue[0]);

  4. The filter parameter should be 'yyyy-MM-dd' instead of 'yyyy-mm-dd' (capital M's), because small m's represent minutes instead of months and will give you this result:

    ["2016-00-29", "2016-00-30", "2016-00-01", "2016-00-02", "2016-00-03"]

Also check full example on plunker.

Upvotes: 1

Related Questions