Is it possible to compare JSON data in MM/DD/YYYY format within a controller to today's date using a custom filter, and then display the filtered list in an array?

I'm struggling to compare today's date obtained from new Date() with a date in MM/DD/YYYY format and then filter the array data using my own custom filter. Is there a way to achieve this? I attempted to set the hours to (0,0,0,0) and compare them but it didn't work as expected. Can we also set hours in JSON data and perform a comparison? Here is a snippet of my JavaScript code, and you can check out the Plunker link here. I can successfully compare id:4 and 5, but struggle with 1, 2, and 3 due to different date formats. My goal was to display data for the last few days based on user input. Any suggestions on how to compare these two dates and filter the required data?

// Code goes here

var app = angular.module('tempfilter', []);

app.controller('MainCtrl', function($scope) {
  $scope.sensordata = [
    {id:'id:1',name:'Rob',Date:"5/11/2014","Temp":42},
 {id:'id:1',name:'Don',Date:"2015-05-11","Temp":42},
    {id:'id:2',name:'Bob',Date:"2015-02-22T17:16:14.720Z","Temp":50},
    {id:'id:3',name:'Tom', Date: new Date().getDate(),"Temp":60},
    {id:'id:4',name:'Sinclair',Date: new Date(),"Temp":65}

  ];
  
  $scope.filter = { value:16490 };
    
});

app.filter('tempo', function() {
    return function( items, field, value) {
      var filtered = [];
      var epoch = new Date(); // today!
      epoch.setHours(0,0,0,0);
      
      epoch.setDate(epoch.getDate()-value);
      
      angular.forEach(items, function(item) {
        if (item[field]>epoch){
          filtered.push(item);
        }
      });
      return filtered;
    };
});

Answer №1

One way to accomplish this is by utilizing the getTime() method of the Date object. Here's an example:

let currentTime = new Date().getTime()
let targetTime = new Date("2019-06-25").getTime()
You can then compare currentTime and targetTime according to your requirements. The getTime() method returns the time in milliseconds since 01/01/1970. I trust this explanation will be beneficial to you.

Answer №2

Just a heads up: I have no experience with angular.js.

Building on Anand's suggestion, have you experimented with using Date.getTime()? By utilizing new Date(), you can create a Date object for all your scenarios and then retrieve the number of milliseconds with getTime(), making comparisons much simpler.

Consider capturing the timestamp at the JSON creation stage to avoid calculating it repeatedly within the loop.

This is how your code could be structured:

// Place your code here

var app = angular.module('tempfilter', []);

app.controller('MainCtrl', function($scope) {
  $scope.sensordata = [
    {id:'id:1',name:'Rob',Date:"5/11/2014","Temp":42},
 {id:'id:1',name:'Don',Date:"2015-05-11","Temp":42},
    {id:'id:2',name:'Bob',Date:"2015-02-22T17:16:14.720Z","Temp":50},
    {id:'id:3',name:'Tom', Date: new Date().getDate(),"Temp":60},
    {id:'id:4',name:'Sinclair',Date: new Date(),"Temp":65}

  ];
  
  $scope.filter = { value:16490 };
    
});

app.filter('tempo', function() {
    return function( items, field, value) {
      var filtered = [];
      var epoch = new Date(); // today!
      epoch.setHours(0,0,0,0);
      
      epoch.setDate(epoch.getDate()-value);

      //At this point
      epoch = epoch.getTime();
      
      angular.forEach(items, function(item) {
        //Here as well
        if (new Date(item[field]).getTime() > epoch){
          filtered.push(item);
        }
      });
      return filtered;
    };
});

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

What is the best way to update the key for the sorting field in a meteor collection query?

I am struggling to replace the name key with a value passed in via a parameter this.params.sortby in the code below. Any help would be appreciated. For example, if: this.params.sortby=location I would like the following: Template.MyTemplate.helpers({ ...

Is your component failing to re-render after a state change?

I am currently in the process of developing a random quote generator. The main feature is a quote box that showcases quotes along with their respective authors. I have implemented a method that triggers upon button click to randomize the list of quotes and ...

Is it possible to forecast an on click event using jQuery?

I have encountered a specific issue. Within my code, there are certain elements, specifically <li> elements, that undergo a particular operation triggered by a click event: $('.panelTabs li').on('click', function () { // ..som ...

Tips on transmitting checkbox data from AJAX to PHP

I'm currently working with this code and facing an issue where data from checkboxes is being sent to PHP one by one. I want to be able to send multiple selected data at once. How can I modify the code to achieve this? $('#lunas').click(funct ...

Obtain a segment of the string pathway

In this scenario, there is a file path provided below. Unlike the rest of the URL, the last part (referred to as video2.mp4) regularly changes. The language used for this project is either Javascript or Typescript. file:///data/user/0/com.sleep.app/files/ ...

Endless waiting in Node JS

I am working on a program that extracts data from a database. However, I am encountering an issue where the program gets stuck in an infinite loading loop. router router.get('/', (req, res) => { res.render('/music', '', ...

How can I implement user account functionality with only JavaScript in an Angular frontend and Node.js/Express server?

Many resources I've come across utilize php or a similar language. With an Angular frontend and Node/express server code in place, but no backend yet, I'm uncertain about how to approach user sign-up. ...

Implementing Hover Effect on Elements within Item template of GridView

I want to update the background color of GridView rows when the mouse hovers over them. It's working fine for columns within <boundfield>, but the background color of labels inside <itemtemplate> does not change on MouseHover. This is how ...

Adding JavaScript in the code behind page of an ASP.NET application using C#

Currently, my challenge involves inserting a javascript code into the code behind page of an asp.net application using c#. While browsing through various resources, I stumbled upon some solutions provided by this website. Despite implementing them as inst ...

{ Node.js and Express - Preventing Duplicate Requests } How to fix the issue of sending client-side requests twice

I'm currently diving into nodejs but this frustrating bug is driving me crazy!! Every time I try to make a POST request on my website, it ends up sending two requests instead of one. Initially, I suspected it was an issue with my connection to mongodb ...

Creating a Node.JS environment with Express and Socket.IO: A beginner's guide

Trying to set up a Node.JS server on port 3800 of my CentOS server and encountering difficulties: var app = require('express')(); var http = require('http').Server(app); app.get('/', function(req, res){ res.send('&l ...

Leveraging HTML5 file uploads alongside AJAX and jQuery

While there are questions with similar themes on Stack Overflow, none seem to quite fit the bill for what I am looking for. Here's my goal: Upload an entire form of data, including a single file Utilize Codeigniter's file upload library So fa ...

The term 'JsonTable' has not been defined in react/jsx-no-undef

When trying to input a JSON value into the JSON table in React, I encountered an error stating "'JsonTable' is not defined react/jsx-no-undef". What steps should I take to resolve this issue? Do I need to import a specific file? import React, ...

Anchoring links on a webpage that provide users with a clear indication of their current position within the page

In the scenario of a single-page website with various sections (divs) and a header containing links to different anchors on the page, there is a desire to have an indicator highlight which anchor the user is currently viewing. An example of this can be s ...

Are there any known issues with Firefox, jQuery, and CSS animations working in tandem?

As I develop a website with jQuery to manage CSS class switching for animations, I have encountered a strange issue. While Google Chrome and Internet Explorer 9/10 work perfectly, Firefox (Aurora 24 and Firefox 23) does not perform the animations smoothly, ...

Utilizing Angular: incorporating a ng-model template into a directive for seamless filtering

I am working on creating a directive that will display the template below and enable easy filtering. The goal is to have the model change when an option from the select list is chosen and a value is entered into the input box. I want the directive to hold ...

Error TS2322: The variable is of type 'BillingSummaryDTO[]' and cannot be assigned to type 'never'

I've been working on a Recharts chart and I'm trying to populate it with data from an API call. Here's my current approach: export default function Billing() { const [chartData, setChartData] = useState([]); const [isLoading, setIsLoadin ...

Toggle visibility of input field in HTML form

Is there a way to make the second password input only visible once the user starts typing in the first input? Additionally, can both inputs be required or none at all? <form name="signUpForm"> ... <input ng-modal="password" type="passw ...

Choose a specific range of dates using only one Bootstrap Datepicker

Currently utilizing Bootstrap DatePicker version 1.8.0 from this repository. I am looking to select a range within a single Bootstrap DatePicker and require the input values to be sorted in ascending order (as shown in the example below). https://i.sstat ...

The need for incorporating a different directive controller within a subdirective

I have a formQuestionnaireItem Directive specified in the template for the formQuestionnaireItemsGroup Directive. In the formQuestionnaireItem directive, I need to include "^formQuestionnaireItemsGroup" The main form: <form name="formQuestionnaire" au ...