How can I convert the date format from ngbDatepicker to a string in the onSubmit() function of a form

I'm facing an issue with converting the date format from ngbDatepicker to a string before sending the data to my backend API. The API only accepts dates in string format, so I attempted to convert it using

submittedData.MaturityDate.toString();
and
submittedData.RemitDate.toString();
, but it's not working as expected.

In my component.html, I have the following form:

<div class="form-group row">
            <div class="col-sm-6">
              <label for="MaturityDate">Maturity Date</label>
              ...
            </div>

            <div class="col-sm-6">
              <label for="RemitDate">Remittance Date</label>
              ...
        </div>
    </div>
</div>

When the form is submitted, the following function is triggered in my component.ts:

onSubmit() {
    this.submitted = true;

    // Validate form
    if (this.accountPayableForm.invalid) {
      return;
    }

    let submittedData = this.accountPayableState;
    submittedData = this.accountPayableForm.value;

    // **CONVERSION TO STRING
    submittedData.MaturityDate.toString();
    submittedData.RemitDate.toString();

    console.log(submittedData);
    
    this.loading = true;
    ...
    );
  }

This is the submitAccountPayable() function in my service.ts:

submitAccountPayable(accountPayable: AccountPayableState) {
    return this.http.post(this.issueAccountPayableUrl, accountPayable);
  }

The attributes MaturityDate and RemitDate in my AccountPayableState model are meant to be strings. However, even after using .toString(), they are not being converted correctly. Here's a snippet of the payload in the console:

BuyerAccount: "asdasdasd"
BuyerCode: "123123"
MaturityDate: {year: 2019, month: 10, day: 18}
OwningAccountKey: "e273b89f-c828-41ad-873d-a13bbe63d7c5"
...
RemitDate: {year: 2019, month: 10, day: 10}
SupplierAccount: "asdasdasda"
SupplierCode: "123123123"

Any advice on how to resolve this issue?

Answer №1

If you want to update your date, consider using a function:

private formatDate = (date) => `${date.year}-${date.month}-${date.day}`; 

onSubmit() {
    this.submitted = true;

    // Check if the form is valid
    if (this.accountPayableForm.invalid) {
      return;
    }

    let submittedData = this.accountPayableState;
    submittedData = this.accountPayableForm.value;

    submittedData.MaturityDate = this.formatDate(submittedData.MaturityDate);
    submittedData.RemitDate= this.formatDate(submittedData.RemitDate);
    submittedData.OwningAccountKey = this.currentAccount[0].accountId;
    ...

Answer №2

When working with the ngbDatepicker, keep in mind that the object it returns is in its default format. To handle this, you can choose to manually convert the date either within your onSubmit function or within the model itself. Alternatively, consider utilizing a custom date adapter for more flexibility. Check out the following link for examples on how to implement a custom date adapter:

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 Map/Reduce function is producing incorrect results because of null values, causing me to receive NaN or erroneous

I am ready to delve into another Map/Reduce query. Within my database, I have a collection named "example" which is structured like this: { "userid" : "somehash", "channel" : "Channel 1" } The Map/Reduce functions I am using are as follows: var map = f ...

Limiting the length of numbers in Material UI

Is there a way to restrict user input to only numbers with a maximum length of 3 in Material UI? <TextField id="score" label="score" className={classes.textField} name="totalScore" margin="normal" defaultValue={score} /> We specifically ...

Can you help me transition my angular website from English to Spanish using a radio button?

I want to develop an Angular website where users can select a language and click the next button to change all text on subsequent pages to that chosen language. For example, if a user selects Spanish, then all text on the following screens will be in Spani ...

The tooltip callback in react-chartjs-2 is failing to function as expected

I've been utilizing the react-chartjs-2 library to create basic charts in my React project. In an attempt to customize the tooltip, I added a title: tooltips: { callbacks: { label: (tooltipItem, data) => { return tooltipItem?.valu ...

In Vue, the CropperJs image initially appears small, but it returns to its original size after editing

I encountered a peculiar issue while working on a website for image cropping using Vue.js and CropperJs. On the homepage, users can select an image to crop and proceed to the next page where a component named ImageCropper.vue is displayed. Strangely, the c ...

Using React, retrieving the value of a checked radio button from the state

My issue involves a list of radio buttons generated from a map loop containing numbers like 1, 2, and 3. When I select a radio button, it should set a state: <ul className="flex gap-6 justify-center"> {maxPaxArr.map((keypax) => ...

Using Javascript and jQuery to modify the element's ID

I've been trying to automate the loading process of articles on my website, but I'm having trouble with the line $(tytul).html(data);. Is there a way to get this working correctly? var numboart = 3; $(document).ready(function(){ for(i=0;i& ...

Most effective method for initiating model class attributes

Is there a more efficient way to initialize model classes without explicitly defining each member as undefined? The original concept was to be able to simply use super(data); in extended classes. class Model { construct(data: any) { Object.ke ...

Struggle with typescript integration with emotion and styled components

Issue Description: I encountered an issue while working with typescript and emotion/styled libraries. When attempting to specify the type of the parent component that wraps a styled component, I faced difficulties. The scenario involves a parent componen ...

Enable the use of unfamiliar techniques on object

I am facing a challenge with an object that contains multiple method names which are not known at compile time. The signature of these methods always remains the same, but I am unsure about how to handle this scenario. I attempted to utilize an index type ...

The blinking cursor in Google Docs is known as "kix-cursor-caret."

Although I adore Google Docs, I can't help but find the blinking cursor a bit too distracting for my liking. It seems that the latest version of Google Docs fails to comply with the operating system's setting for displaying a solid, non-blinking ...

Creating a popup trigger in ReactJS to activate when the browser tab is closed

I am currently working on an enrollment form that requires customer information. If a user fills out half of the form and then attempts to close the tab, I want to trigger a popup giving them the option to save and exit or simply exit. While I have a jQue ...

Exploring the capabilities of batch updates in Firestore with the latest web version-9

I am facing issues when trying to update certain values in my firestore collection within my nuxt project. const batch = writeBatch(firestore); const data = query(collection(firestore, `notifications`, `${uid}/news`)); const querySnapshot = await ...

Leveraging the power of Bootstrap and JavaScript to implement a custom Toast feature

I am utilizing Bootstrap 4 to design Toasts, and I am presently developing a JavaScript function to generate a toast. My attempt to create elements within the JS file did not properly style it. index.html <!doctype html> <html lang="en"> ...

Troubleshooting code: JavaScript not functioning properly with CSS

I am attempting to create a vertical header using JavaScript, CSS, and HTML. However, I am facing an issue with the header height not dynamically adjusting. I believe there might be an error in how I am calling JSS. Code : <style> table, tr, td, t ...

The Material UI React Table onCellClick event is not triggering as expected when clicking on a

I am facing an issue with my react component that contains a material UI Table. I want to add an onCellClick event to each row of the table, but when I add it to each TableRow individually, the event doesn't get fired. However, if I add it to the Tabl ...

Incorporating code execution during promise completion

I'm currently working on an express application that involves a generator function which takes approximately 5 minutes to process a large amount of data. Unfortunately, I am unable to optimize this function any further. Express has a built-in ti ...

Executing a jQuery AJAX function when the timeout occurs

My goal is to dynamically reload my jQuery DataTables without having to refresh the entire page in order to fetch new data. Here's the initial function I have set up to kick off the process: $(document).ready(function() { $.ajax({ url:&apo ...

How to retrieve a value only if it is truthy in JavaScript or TypeScript - Understanding the operator

In React components, a common scenario arises with code like this: <Carousel interval={modalOpen ? null : 8000}> It would be great if I could simplify it to something along these lines (although it's not valid): <Carousel interval={modalOpen ...

Having trouble passing multiple associative array values from JavaScript/AJAX to PHP

We have been encountering an issue when trying to pass multiple associative array values from JavaScript/AJAX to PHP, as the PHP file is receiving an empty object/array. Could someone kindly assist us in retrieving the values of an associative array from ...