ZombieChowder
ZombieChowder

Reputation: 1204

How to compare a date to a string in JavaScript?

I am currently trying to create a custom filter which will display the latest up to date file in my system. I am using AngularJS in order to filter my listed data.

The issue that I am having is that my date data is stored as a string in my json file and I am not sure how to filter it so it.

My idea was to create a custom filter by storing today's date as a variable and comparing it to the json file stored date.

Here is how my json file looks:

{
    "data": [

        {
            "title": "Something Exciting",
            "description": "A TV show about something really exciting.",
            "date": " 06/2017",
            "link": "../pdf/whoReadsBooksAnyway.pdf"
        },
        {
            "title":"Stranger Things",
            "description":"Getting back that 80's Steven King Vibe",
            "date": "05/2017",
            "link": "../pdf/AllAlongTheWatchTower.pdf"
        }
    ]
}

I need to display the items by the latest date field, so I started creating a custom filter:

 app.filter('dateFilter', function($scope){

         $scope.getDatetime = new Date();

         var aaa = "../../../views/TvShows/json/shows.json"
         $http.get(aaa).then(function maybe(response, date){
                $scope.data = reseponse.data.data;
            });

        if($scope.getDatetime < $scope.data.date){
            return $scope.myFilter;
        } else{
            console.log("it didn't work");
        }
    });

The idea behind the filter is to catch the date with an http request and compare it to $scope.GetDatetime which is the current date. I am not really sure how to build the filter. xstatsx is just a $scope object that I return from my initial http get request.

   var xurlx = '../../../views/TvShows/json/shows.json'
            $http.get(xurlx).then(function(response, data){
                $scope.xstatsx = response.data.data; 
            });

In my HTML I am using this to filter and display only the most recent date:

  <div class="well well-lg" style="display: inline-block;" ng-repeat="n in xstatsx | orderBy: '-date'" ng-show='0 == $index'>

How can I filter my output so it shows only the latest up to date listed files?

Upvotes: 0

Views: 118

Answers (1)

fahad
fahad

Reputation: 139

Try this :

 reseponse.data.data.forEach((item)=>{
  let date = new Date(),
    split = item.date.split("/");
  date.setDate(1);
  date.setMonth(+(split[0]) - 1);
  date.setYear(split[1]);
  item.sort = date;
});  

and use orderBy filter sort key in html

<div ng-repeat="n in xstatsx | orderBy : 'sort' " ></div>

Upvotes: 1

Related Questions