Андрей Гузюк
Андрей Гузюк

Reputation: 2164

How to sort string date angularjs

How sort string date format 24.01.2017 ( descending ) I tried with Date.parse('24.01.2017'); -> but incorrect format

How sort date like this? in controller or view Thanks

Getting data from api want sort by _title enter image description here

Upvotes: 0

Views: 1666

Answers (1)

Fissio
Fissio

Reputation: 3758

Try the orderBy filter with a custom comparing function:

JS:

$scope.entries = [
  {date: '05.02.2001'},
  {date: '01.20.1930'},
  {date: '03.20.2020'} 
]

$scope.compareDates = function(date1, date2) {
  console.log(date1)
  var split1 = date1.value.split('.');
  var split2 = date2.value.split('.');

  var date1compare = split1[2] + split1[1] + split1[0];
  var date2compare = split2[2] + split2[1] + split2[0];

  return (date1compare > date2compare ? 1 : -1)
}

HTML:

<div ng-repeat="entry in entries | orderBy:'date':false:compareDates">
    {{entry.date}}
</div>

Plunker: https://plnkr.co/edit/LETAFDoD5fub63tKI5Ne?p=preview

Upvotes: 1

Related Questions