To retrieve JSON objects depending on today's date

My data is stored in a JSON file named tasks. The structure of this template can be visualized as follows:

https://i.sstatic.net/MCSit.png

Data Structure of JSON File

[
  {
    "taskName": "Task - 1",
    "id": "01",
    "startDate": "2019-04-17T18:30:00Z" <==========
  },
  {
    "taskName": "Task - 2",
    "id": "02",
    "startDate": "2019-04-22T14:30:00Z"
  },
  {
    "taskName": "Task - 3",
    "id": "03",
    "startDate": "2019-04-17T12:30:00Z" <========
  },
  {
    "taskName": "Task - 4",
    "id": "04",
    "startDate": "2019-04-25T18:10:00Z"
  }
]

In the JSON file, there is a property called startDate, based on which I aim to display relevant tasks like this:

https://i.sstatic.net/0jHIh.png

I attempted filtering by date with the following code snippets:

HTML Implementation

<div class="cust-detail" *ngFor="let task of getTaskByDate(myDate)">
    <tr>
        <td>Task Name: </td>
        <td>{{task.taskName }}</td>
    </tr>   
</div>

Typescript Implementation

  tasks: ITasks;
  myDate = new Date();

  constructor(private myService: MyService) {}

  ngOnInit() {
    this.myService.getTasks()
      .subscribe(res => this.tasks = res);
  }


    public getTaskByDate (myDate: string): ITasks  {
    return this.tasks ? this.tasks.filter(x => x.startDate === myDate) : [];
  }

If you'd like to explore a live demo showcasing this functionality, check it out here

Answer №1

When working with your html code, you currently have the line

let task of getTaskByDate(myDate)
where myDate = new Date();. In this case, it would be more accurate to change
public getTaskByDate (myDate: string): ITasks
to
public getTaskByDate (myDate: Date): ITasks

Once that adjustment is made, comparing the Dates becomes a straightforward process:

The first method involves altering the filter rule:

new Date(x.startDate).toDateString() === myDate.toDateString()

The second method includes:

public getTaskByDate (myDate: Date): ITask[]  {
      const dateString = myDate.toJSON().substr(0, 10);
      return this.tasks ? this.tasks.filter(x => x.startDate.substr(0, 10) === dateString) : [];
  }

In addition to resolving the issue at hand, consider renaming the interface from ITasks to ITask and ensuring the AppComponent property is of type ITask[], as the current naming convention may be misleading. While editing, remember to update the type of myDate to Date (

getTaskByDate (myDate: string): ITasks
should become
getTaskByDate (myDate: Date): ITask[]
since myDate has always been a Date)

Answer №2

It's important to keep in mind two key factors:

  1. The startDate property is a string type, so comparing it with a Date object directly won't work; it must first be converted into a proper Date.
  2. The startDate also includes a time component, so this has to be considered in any comparison.

One solution involves using the date-fns library (which allows for tree-shaking) to filter tasks based on dates only (without considering time):

  • To install Date-Fns, run npm i date-fns.
  • Include these imports in your TypeScript file:
    import { addDays, parse, startOfDay } from 'date-fns';
public getTaskByDate (myDate: string): ITasks  {
  const date = parse(myDate);                    // parsing input string
  const startOfSearch = startOfDay(date);         // beginning of the day
  const endOfSearch = addDays(startOfSearch, 1);  // start of next day

  return this.tasks ? this.tasks.filter(x => {
    const parsedDate = parse(x.startDate);
    return parsedDate >= startOfSearch && parsedDate < endOfSearch;
  }) : [];
}

For those not utilizing Date-Fns, a solution focusing solely on matching dates can be achieved like so:

public getTaskByDate (myDate: string): ITasks  {
  const date = Date.parse(myDate);               // parsing input string

  return this.tasks 
    ? this.tasks.filter(x => Date.parse(x.startDate).toDateString() === date.toDateString()) 
    : [];
}

Answer №3

Below is the HTML that your filter will work with:

<h4>Today's Task</h4>
<div class="cust-detail" *ngFor="let task of getTaskByDate(myDate)">
    <tr>
        <td>Task Name: </td>
        <td>{{task.taskName }}</td>
    </tr>   
    <hr>
</div>

The filtering function in the code snippet above filters objects based on

myDate = new Date().toDateString()
. This method converts the date to a string like 'Wed Apr 17 2019', excluding minutes and seconds. Although comparing two strings may not be the most optimal choice, it serves as a workaround solution.

public getTaskByDate (myDate: string): ITasks  {
    return this.tasks ? this.tasks.filter(x => new Date(x.startDate).toDateString() === myDate) : [];
}

I made changes to your Stackblitz project here: https://stackblitz.com/edit/angular-movie-read-load-json-sample-eg-muxfzr

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

Error: Could not inject CookieService - No provider found for CookieService

I am currently working on an ASP.NET Core 2.0 project that incorporates an Angular 5.1.0 ClientApp in Visual Studio 2017 v15.4.5. My goal is to utilize the ngx-cookie-service within this setup. After closely following the provided instructions for importi ...

Why is it that I am able to invoke my Redux action creators from the componentWillMount() method, but not from my event handler function?

I'm currently developing an application using React, Redux, and TypeScript. My Redux store is all set up with initial state and it's working fine in populating my components. Now, I am in the process of connecting a form that will trigger my act ...

Obtain an instance tuple from tuple classes using TypeScript 3.0 generic rest tuples type

When it comes to retrieving the correct instance type from a class type, the process typically involves using the following code: type Constructor<T = {}> = new (...args: any[]) => T class Foo {} function getInstanceFromClass<T>(Klass: Co ...

After transforming an angular project into an npm module, where should the html, css, and other files be placed? Additionally, what is the process for converting a project into

I am looking to modify the ngx-material-timepicker node module by making changes to the basic HTML and CSS of the project. However, I have found that there are no HTML or CSS files available in the node_modules-> ngx-material-timepicker folder, only TS ...

Disabling an attribute/element from change detection in Angular

Let's say I have the following code in my template: <img src="..." alt="myService.getImgAlt()" /> This works fine, but calling this function at every change detection can impact performance negatively. Is there a way to excl ...

Discover the initial item in Observable that meets a certain criteria

I am trying to retrieve the first item of type avatar from payload.result within an observable: let result = this.fileService.getAvatarByUserId(2).pipe( map((payload: Payload<FileModel[]>) => payload.result), first((result: FileModel[]) => ...

TypeScript Definitions for Material-UI version 15

Is there a Material-UI v15 TypeScript definition file in the works? I need it for a project I'm working on and as a TypeScript newbie, I want to make sure the custom file I've begun is accurate. ...

Converting an array of objects into a TypeScript dictionary with IDs as the key mapping

Is there a way to provide type hints for better autocompletion when accessing keys like dictionary.Germany from the following data and types? type Entry = { tld: string; name: string; population: number; }; const data: Entry[] = [ {tld: 'de&a ...

Unable to execute OAuth2 with Okta using angular-oauth2-oidc framework

Looking to create an authentication module for an Angular application using Okta as the identity provider and implementing the angular-oauth2-oidc flow. Following a guide here: . However, encountering errors when running the web app. How can I troubleshoot ...

Having trouble retrieving the Ionic 2 slides instance - getting a result of undefined

As I attempt to utilize the slides and access the instance in order to use the slideto functionality programmatically, I find myself encountering the issue of receiving 'undefined' back despite following the documentation. Here is my TypeScript ...

Asynchronous function in TypeScript is restricting the return type to only one promise type

Using node version 14.7.0, npm version 6.14.7, and typescript version 3.7.3. I have a function that interacts with a postgres database and retrieves either the first row it finds or all results based on a parameter. It looks something like this: async fet ...

Checkbox in Angular FormGroup not triggering touched state

There seems to be an issue with the Angular form when checking if the form is touched, especially in relation to a checkbox element. Despite the value of the checkbox changing on click, I am seeing !newDeviceGroup.touched = true. I'm not quite sure wh ...

Mandatory classification eliminates understanding of function type

I'm currently trying to transform an optional argument from one type into a required one in my type definition. However, I am encountering some difficulties and can't seem to figure out what I'm doing wrong in the process. Would appreciate a ...

This constructor is typically not suitable for Angular Dependency Injection, unless it is explicitly allowed

The error I am encountering seems to only occur during testing. When I build with -prod, everything works fine. The demo application project that utilizes the built library is able to fully interact with all the parameters of the services in question. I am ...

Why is the data retrieved using ActivatedRoute.snapshot.data['']?

Recently delving into Angular, I stumbled upon this snippet of code: export class ProductListComponent implements OnInit { private Products: Product[]; constructor(private _activatedRoute: ActivatedRoute) { } ngOnInit() { this.Produc ...

What is the best way to utilize an "as" property in TypeScript when forwarding props to a component?

I am currently working on creating a collection of components, and I require some of them to have the option of a customizable tag name. For instance, there are times when what seems like a <button> is actually an <a>. Therefore, I would like t ...

Angular: leveraging the power of *ngFor and *ngIf while incorporating index values in nested components

I want to display various items from an array observable within grid-card components. I also aim to restrict the number of grid cards displayed based on specific variables in my component, such as gridCols*maxRows, by utilizing a conditional check with *ng ...

Obtain an array containing only one property value from an array of objects

Within my array of objects, I am looking to extract all the controls and move them to a new array: this.formModel = { sections: [ { title: 'Section 01', controls: [ new FormControlInput({ ...

Obtaining only the updated objects from a web API in C#

When fetching data from a c# web api to my angular app, I notice that all the data is being polled every time, even if most of it remains unchanged. What I really want is to only retrieve and update the objects that have been modified in some way. Here&ap ...

Anticipate that the function parameter will correspond to a key within an object containing variable properties

As I develop a multi-language application, my goal is to create a strict and simple typing system. The code that I am currently using is as follows: //=== Inside my Hook: ===// interface ITranslation { [key:string]:[string, string] } const useTranslato ...