How to format a Date object as yyyy-MM-dd when serializing to JSON in Angular?

I have a situation where I need to display an object's 'birthDate' property in the format DD/MM/YYYY on screen. The data is stored in the database as YYYY-MM-DD, which is a string type. I am currently using bootstrap bsDatePicker for this task. In order to submit any modifications, I need to convert the displayed date to match the database format.

Could you provide guidance on how to serialize the Date (DD/MM/YYYY) to the format YYYY-MM-DD when making a JSON request?

Are there any clever techniques to optimize this conversion without altering the database structure?

Thank you for your assistance!

Answer №1

To start off, you'll need to create a function that takes in a string containing a date and then converts it. Towards the end of the function, there is some clever ternary logic implemented because without it, the date might appear as 2018-4-2 instead of the desired 2018-04-02.

formatDate(inputDate:string):string{    
   const currentDate = new Date(inputDate);        
   const dayOfMonth = currentDate.getDate()+1; 
   const currentMonth = currentDate.getMonth()+1;
   const currentYear = currentDate.getFullYear();

   return `${currentYear}-${(currentMonth < 10 ? ("0" + currentMonth) : currentMonth)}-${(dayOfMonth < 10 ? ("0" + dayOfMonth) : dayOfMonth)}`;    
 }

Answer №2

One way to go about it is by converting the string into a suitable format for JSON submission. You can achieve this by using a helper function like the following:

    formatDate():string{    
        const today = new Date();        

        const day = today.getDate(); 
        const month = today.getMonth()+1; // To convert from 0-11 to 1-12
        const year = today.getFullYear();

        return year+"-"+month+"-"+day;    
    }

This function will output "2018-10-19".

Answer №3

Appreciate all the feedback, this is my approach:

I utilized reflection to map the original object to the request type for handling dates:

if(item[key] instanceof Date) {
  value = this.dataPipe.transform(item[key], 'yyyy-MM-dd').toString();
}else {
  value = item[key].toString();
}

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

Issues with Formik sign-up

Working on a study project involving React, Typescript, Formik, and Firebase presents a challenge as the code is not functioning correctly. While authentication works well with user creation in Firebase, issues exist with redirection, form clearing, and da ...

Error: Unexpected token < occurs when using SVG require in Jest

I'm struggling to locate the source of this error. Currently, I am working with Typescript in React and using Jest and Enzyme for unit testing. Below is a snippet from my Package.json file: "scripts": { "start": "node server.js", "bundle": ...

Incorporating JSON data into an array using d3

I'm currently working on mapping JSON data to an array variable in d3. Below is the JSON I am using: [ { "Impressions": "273909", "Clicks": "648", "CPM": 4.6388278388278, "Cost": 1266.4, "CPC": 1.9543209876543, "Campaign": "C ...

Ways to broaden React categories for embracing html attributes as props?

When designing a component that accepts both custom props and HTML attribute props, what is the best approach for creating the interface? The ideal interface should also accommodate React-specific HTML props, such as using className instead of class. Here ...

What is the best way to transform XML.gz files into JSON format?

I have recently started working with XML and I am trying to send a GET request to an endpoint to retrieve some data. The response I am getting back is in xml.gz format, but I would like to convert it to JSON on my node server. Is there a way for me to acco ...

Uninstalling NPM License Checker version

Utilizing the npm license checker tool found at https://www.npmjs.com/package/license-checker The configuration in license-format.json for the customPath is as follows: { "name": "", "version": false, "description&quo ...

In Typescript, a function that is declared with a type other than 'void' or 'any' is required to have a return value

I'm a beginner in Angular2/Typescript and I am encountering an error while trying to compile my project: An error is showing: A function that has a declared type other than 'void' or 'any' must return a value. Here is the code sn ...

Refresh a Google chart without having to reload the entire page

I currently have a button that allows me to refresh the data on my page in case there is new data available through an API. Although this button successfully refreshes my datatable, it does not redraw the Google charts I have integrated into my project usi ...

Issue with subscribing to a shared service in Angular 2

I've encountered some challenges with BehaviorSubject while using a shared service across three components: import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable() export ...

It is feasible to completely override a class in TypeScript

I have a subclass defined as follows: customException.ts /** * Custom Error class. * * @class Error * @extends {Error} */ class Error { /** * @type {string} * @memberof Error */ message: string; /** * @type {boolean} * @memberof ...

Combining strings with objects in Javascript: A step-by-step guide

In the code snippet provided, I am combining variables to create a path to another existing object and its attribute. The issue is that I always receive a string, but I would like to somehow convert it into an object. // SET CUSTOM CONTENT FOR COLUMN IF ...

displaying a pair of inputs next to each other

Is it possible to display two input fields side by side? I am using Angular's matInput forms, but struggling to position the second input next to the first. What I would like to achieve is to have "input1 , input2" on the same line. Here is my code: ...

How can we retrieve an API response using Fetch, manipulate it with JSON.stringify(), and what are the next steps in

After countless attempts, I still can't figure out what's missing here. I'm utilizing fetch to retrieve data from Mapbox: var response = fetch(myURL) .then(response => response.json()) .then(data => console.log(JSON.stringify(data))) ...

Mastering the art of grouping by a key and generating sub-objects from a plain array of key-value pairs in JavaScript ES5 without relying on third-party libraries

My dataset consists of an array of objects, each containing 4 keys: [ { "team": "USA", "team_profile_id": "10", "player": "Captain America", "player_id": "10X1" }, { "team": "USA", "team_profile_id": "10", "player": "The ...

Create an AngularJS task manager that saves your to-do list even when the page is refreshed

Currently, I am developing a straightforward to-do list application using AngularJS within an ASP.NET MVC template. Surprisingly, I have successfully integrated Angular and Bootstrap to achieve the desired functionality. The app allows users to add and re ...

Using JavaScript to call an API in PHP and determine how to handle a response that is not equal to 200 by printing an

Greetings! I am aiming for a scenario where, upon clicking the link, the user's parameter is transferred to JavaScript. This parameter will then be used in ajax to trigger a call to my PHP file containing the API. The API, after processing the parame ...

Enhance your TypeScript code using decorators with inheritance

Exploring the realm of Typescript decorators has led me to discover their intriguing behavior when combined with class inheritance. Consider the following scenario: class A { @f() propA; } class B extends A { @f() propB; } class C exten ...

Is there a way to establish communication between two components without relying on the @input and @output decorators?

Is there a way to establish communication between two components without relying on the @input and @output decorators? During a recent interview, I was asked about component interaction based on keypress events. The challenge was to have any keystroke ent ...

Having trouble with typecasting in Angular 9 after receiving an HTTP response?

When initializing my component, it fetches student information from an API. Here is the ngOnInit code for component-version1: ngOnInit(): void { if(!this.student) { this.studentsService.getStudentDetail(this.id).subscribe( (response: Stu ...

Comparing JSON strings

In the midst of a C++ project, I find myself struggling to compare multiple JSON strings that are passed as arguments in a function. The goal is to return a boolean based on their comparison. While using Jsoncpp for this task, I've encountered challen ...