Ways to evaluate a date against a string in JavaScript

I am currently working on developing a custom filter to showcase the most recent file in my system using AngularJS for data filtering.

The challenge I am facing is that the date information is saved as a string in my json file, and I'm unsure how to filter it appropriately.

My approach involves creating a custom filter by defining today's date as a variable and comparing it with the date stored in the json file.

Below is a snippet of my json file structure:

{
    "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 aim to display items based on the latest date field, hence the creation of 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 filter is designed to fetch the date through an http request and compare it to $scope.GetDatetime which represents the current date. I'm still figuring out the filter implementation. xstatsx is a $scope object obtained from the initial http get request.

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

To filter and display only the most recent date in my HTML, I use the following:

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

Any suggestions on how I can effectively filter and display only the latest updated files?

Answer №1

Give this a shot :

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

then apply the orderBy filter using the sorted key in your HTML

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain how to utilize a function on a client component in Next.js?

I'm a bit lost on how client components function. I am working on an image uploader project where I need to extract the userId from supabase, utilize the supabase server function, and then upload the image to supabase storage with the "userId/filename ...

Displaying imported JSON data in a tabular format

I am struggling with writing a function in my VueJS template that sends a request to the backend API with a specific key and then displays the JSON response in a table. For example, here is a sample of the JSON data: {"driver_id":1,"driver_name":"{driver ...

What is the process of removing a document with Next.JS and MongoDB by utilizing next-connect?

Currently in the process of constructing my first CRUD application using NextJS/Mongodb and I've decided to utilize next-connect for handling the methods. As a newcomer to this field, I have managed to successfully create posts and update user profile ...

Events in the backbone view fail to trigger after a re-render

For some reason, I am struggling to get mouse events to work on my backbone view after it is re-rendered. It seems like the only solution is to use a rather convoluted jQuery statement: $("a").die().unbind().live("mousedown",this.switchtabs); I initially ...

AngularJS directive attribute 'at' choices

Encountered an issue while using an AngularJS directive. Here is the problem: directives.js: var directives = angular.module('directives', []); directives.directive('list', ['$templateCache', function() { re ...

Countdown timer feature and auto-submit function for your website's page

Currently, I am working on an online exam project that requires the page to be automatically submitted after 10 minutes, regardless of whether the user clicks on the submit button or not. Additionally, I want to include a countdown timer to display the r ...

Tips on sending/posting a JSON request on a Windows Phone

Is there a way to send a request using JSON content in a Windows Phone? I have the JSON parameters ready, but not sure how to post it. ...

displaying a div as a pop-up within an ASP.NET MVC 4 web application

One aspect of my asp.net MVC 4 application involves a partial view structured like so: <form class="qty-add" action="#" method="POST"> <label>Qty:</label> <div class="inp-controller"> <a href="#" c ...

Angular directive using ng-if to display image

I have the following code in my showCtrl: $scope.showTeam = function(){ var count = 0; for (var k in subordinates) { if (subordinates.hasOwnProperty(k)) { ++count; } } if(count > 0){ r ...

Trouble arises when trying to define the style for an element generated through the Document

I'm having trouble setting the style for a 'tr' element created using DOM within JavaScript. Here's the code snippet: var tr = document.createElement("tr"); tr.onmouseover=function(){this.style.backgroundColor='#fbf9e0';}; ...

Leverage ObjectMapper for parsing nested Dictionaries in Swift

My previous JSON format looked like this: { "parameters": { "customerId": 9, "from": "2014-06-05T14:00:00", "until": "2014-06-05T15:00:00", "km": 20, "insurance": false }, "estimatesPerCategory": { "2": { "timeCost": 5, "kmCost": 6, ... } For ...

How to access the onchange text in a react-select search component

I'm currently working on implementing search select functionality in my webpage using the react-select-search npm package. This is my main component: import React, { Component } from "react"; import Task from "./task"; // Rest of ...

Create a list of objects by recursively looping through a JSON object

I am currently working on extracting an array of custom objects: The challenge lies in parsing a JSON object that contains a series of questions. These questions may have sub-questions, and each sub-question may further contain others. The structure of my ...

Ionic's select feature fails to include an object in the options

I'm experiencing an issue where I cannot successfully add a mongoose object to another mongoose object using a select bar within a form. Surprisingly, all the other key-value pairs are inserting correctly, including the checkbox bool. However, for som ...

Attempting to navigate a tutorial on discord.js, I encountered an issue labeled as "Unknown application" that disrupted my progress

I attempted a tutorial for discord.js, but encountered an error message saying "DiscordAPIError[10002]: Unknown Application." Even though I checked my clientID and applicationID and they seem to be correct! You can find the tutorial here. Here is the co ...

Tips for incorporating a value within the AngularJS select function

Having an issue with passing a list value in the html select method using AngularJS. Here is my code: app.js $scope.subcategory = function() { var query = "SELECT unit FROM Length;"; $cordovaSQLite.execute(db, query).then(function(res) { ...

Connect a series of numerical input fields in Vue.js

One of the tasks I'm working on involves managing a table filled with rows of information. Users can choose multiple rows by checking checkboxes in each row, and I need to keep track of how many rows are selected by updating the totalSelected value. ...

Manipulate the 'i' variable within a for loop using JavaScript, JQuery, and JSON to modify an attribute

I have 4 picture locations saved in a JSON file named img0, img1, img2, and img3. By using an AJAX call (getJSON), I retrieve the data from the file and then assign them to the "src" attribute of the images on my webpage. Everything works fine with this c ...

What are the steps for utilizing ckeditor to send textarea information via ajax?

Here is the code snippet that controls the textarea in my chat application: <div class="chat"> <div class="messages"></div> <textarea class="entry" name="entry" placeholder="Welcome to the Chat. Enter your message here!">&l ...

Ways to display data from specific columns using their names in a pair of dropdown lists

I am faced with the challenge of creating a drop-down menu containing column names from a database table. In addition, I need to implement another drop-down menu. My goal is to have the values of the selected column name from the database table displayed ...