Incorrect date format sent to backend through API

Within my Angular + Angular Material application, I am facing an issue with a date range picker. My goal is to send the selected start and end dates in a formatted manner through an API call. However, when the date values are sent over the API as part of the payload, they include the whole date with hours, minutes, seconds, time zone, etc. I only want to send a formatted date (e.g., 2023-09-11).

Despite formatting the date on my end, upon clicking "apply" on the form, the date sent in the payload still includes the complete information. Why is the datepicker overriding my formatted date, or could there be a mistake in my code?

In the component.html file:

<mat-form-field appearance="fill">
    <mat-label>Enter date:</mat-label>
    <mat-date-range-input ngModel [formGroup]="range" [rangePicker]="picker">
        <input matStartDate formControlName="start" placeholder="Start date" >
        <input matEndDate formControlName="end" placeholder="End date">
    </mat-date-range-input>
    <mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-date-range-picker #picker>
        <mat-date-range-picker-actions>
            <button mat-button matDateRangePickerCancel>Cancel</button>
            <button mat-raised-button color="primary" matDateRangePickerApply (click)="getSingleCustomerRangeChartData($event)">Apply</button>
        </mat-date-range-picker-actions>
    </mat-date-range-picker>
</mat-form-field>

In the component.ts file:

setDate: any = new Date().toISOString().substring(0, 10);
range: FormGroup; 

constructor() {
    this.range = new FormGroup({
        start: new FormControl(this.setDate),
        end: new FormControl(this.setDate),
    })
}

getSingleCustomerRangeChartData(event: any) {
    const id = Number(this.route.snapshot.paramMap.get('id'));
    this.customerService.getSingleCustomerRangeChartData(id, this.range.value).subscribe(
      data => {
          this.prodajaChart = data;
          console.log('Selected dates: ', this.range.value);
      },
      error => {
          console.log('Error', error);
      });
}

In the service.ts file:

getSingleCustomerRangeChartData(id:number, range: any) {
    let queryParams = new HttpParams();

    Object.keys(range).forEach((key) => {
        if (range[key] !== null) {
            queryParams = queryParams.append(key, range[key]);
        }
    });

    return this.httpClient.get<typeof prodajaChart>(`${environment.apiUrl}stat/sale/${id}`,{params:queryParams})
}

Answer №1

Currently, it appears that you are only formatting the initial date here.

setDate: any = new Date().toISOString().substring(0, 10);

However, it is important to also format the selected value in this.range.value before sending it to the server later on.

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

The method hasOwnProperty does not function as intended

Upon receiving a JSON object from the server ({error:true}), I attempted to verify if the key "error" exists. Surprisingly, the function hasOwnProperty returned false. Here is the snippet of code that led to this unexpected result: $http({ header ...

Utilizing Node and Express to transform an array into a "Object" Map

For my latest project, I decided to build a web application using Node Express for the backend and Vue for the front end. While working on it, I encountered an issue where an array in an object was being converted to a map when sent to Express via jQuery. ...

A guide on effectively utilizing BehaviorSubject for removing items from an array

Currently, I am working on an Angular 8 application that consists of two components with a child-parent relationship. It came to my notice that even after removing an item from the child component, the item remains visible in the parent component's li ...

Assign a class to a DIV element depending on the ID of an object using Angular

I'm trying to dynamically add a class to a div based on the id of a field in an object. However, my code doesn't seem to be working as expected. Can someone help me debug this? <ng-container *ngFor="let item of cards"> <d ...

``Incorporating Vue.js: A Guide to Emphasizing the Chosen Selection from Numerous Lists

I am currently utilizing Vue.js and have multiple lists displayed, but I only wish to select and highlight one element at a time. Currently, every click results in multiple items being highlighted. I hope that explanation is clear. Below are the snippets o ...

Automatic Expansion Feature for HTML Tables

http://jsfiddle.net/bzL7p87k/ In my table, placeholders are filled with special words. However, what happens when I have more than 4 rows? For instance, if there are 21 placeholders for 21 rows? What I mean is this: I only have one row with a placeholder ...

Ways to eliminate the blue selection box when dragging canvas objects in fabric framework

I've been trying to find a solution to remove the annoying blue highlight box that appears when dragging on the canvas while using fabric js, but so far I haven't had any luck. I've tried the following code, but it only works for text and n ...

How can I display the output from Geocoder in a text box using the ArcGIS JavaScript API?

I am trying to customize the Geocoder text box in the ArcGIS JavaScript API by overriding the default search result. Although I have written some code for this purpose, I am not satisfied with the results. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...

Encountered a Dojo error of "TypeError {stack: (...), message: "undefined is not a function"}" when attempting to display a gif during an ajax load

I've been attempting to display a loading gif while an ajax call is in progress. However, I encountered an error at the show statement and the console displayed: TypeError {stack: (...), message: "undefined is not a function"} Here's my code sn ...

Can dynamic attributes be used with ternary operators in Angular?

I attempted to alter the id of a div using Angular and implemented the following code: <div [id]="'item_' + (itemName !== undefined ? itemName.replace(' ', '-').toLowerCase() : '')"> However, when I run my te ...

Transforming a JavaScript variable into a PHP variable

Is there a way to convert a JavaScript variable obtained from videoel.getCurrentTime function into a PHP variable, so that it can be included in an SQL Insert Query like INSERT INTO tblData VALUES ('$phpVarFromJavascript')? ...

Encountering "token_not_provided" error message on all GET routes in Laravel 5.3 with JWT authentication

I'm currently working on implementing authentication using Laravel 5.3 and Angular 2 with JWT. The authentication part is functioning properly, and I am able to successfully obtain the token. However, when attempting to navigate to any GET routes, an ...

What is the best way to pass information between Express middleware and endpoints?

Many middleware packages come with factories that accept an options object, which often includes a function to provide necessary information to the middleware. One example of this is express-preconditions: app.use(preconditions({ stateAsync: async (re ...

When rendering inside *.map in React, the first object of the array may not be rendered

When the SearchCard component is being rendered, it seems to be skipping the first object in the array- const cardArrayTrackSearch = this.state.searchtrack.map((user, i) => { return ( <SearchCard key={i} reload={th ...

Module 'serviceAccountKey.json' could not be located

I'm encountering an issue while trying to incorporate Firebase Functions into my project. The problem lies in importing the service account key from my project. Here is a snippet of my code: import * as admin from 'firebase-admin'; var ser ...

How can I use AJAX to read an image file and display it on a Canvas?

Is there a way to read an image from my server using Ajax and then display it on Canvas? I am aware that this can be achieved by using normal image tags and canvas draw methods, as shown below: <img id="myImage" src="./ColorTable.PNG" style="display:n ...

MongoDB does not treat aggregate match pipeline as equal to in comparisons

I've been tackling an aggregate pipeline task for MongoDB where I need to retrieve items that do not have a specific user ID. Despite my efforts, I'm struggling to get it right. I attempted using $not, $ne, and $nin in various ways but couldn&ap ...

Creating a "Container" component in Vue.js step by step

As a newcomer to Vue, I am facing a challenge in implementing a wrapper component similar to React's 'Wrapper' component. Specifically, I want to create a reusable datagrid component using a 3rd-party some-table component and a pagination co ...

Querying an array using the Contentful API

Recently, I've been experimenting with the Contentful API (content delivery npm module) and have encountered a challenge that I'm not sure how to overcome. In my Contentful setup, I have a content type called tag which consists of one field, als ...

What is the process for inferring generic return values in TypeScript methods?

I'm curious about how TypeScript infers return types with generics. When a method that uses a generic type as its return value is called without specifying a generic type parameter, how does TypeScript infer the return type? I know that a generic type ...