0

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);
          });
3
  • because they are not date objects, you need to have dates in your data source Commented Sep 29, 2016 at 14:04
  • How can you put the key, vaule pairs in an array dateDatas? Commented Sep 29, 2016 at 14:04
  • @Angular_10 no they don't have to be in the source...but they do need to be parsed to dates to use the filter Commented Sep 29, 2016 at 14:19

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.