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

`How to Merge Angular Route Parameters?`

In the Angular Material Docs application, path parameters are combined in the following manner: // Combine params from all of the path into a single object. this.params = combineLatest( this._route.pathFromRoot.map(route => route.params) ...

What role does enum play in typescript?

What is the purpose of an enum in typescript? If it's only meant to improve code readability, could we achieve the same result using constants? enum Color { Red = 1, Green = 2, Blue = 4 }; let obj1: Color = Color.Red; obj1 = 100; // IDE does not sh ...

Tips for efficiently saving data using await in Mongoose

Currently, the code above is functional, but I am interested in utilizing only async/await for better readability. So, my query is: How can I convert cat.save().then(() => console.log('Saved in db')); to utilize await instead? The purpose of ...

Enhance your Angular2+ writing skills by delving into the intricacies of subscriptions with `

Seeking assistance to enhance the code structure. I am struggling with understanding switchMap, mergeMap and how to avoid nested subscriptions. this.service .service1('something') .pipe(takeUntil(this.unsubscribe)) .subscribe( (s1result ...

Exploring how to work with JSON request data in CakePHP

I have just received the following payload from Gitlab. { "object_kind": "push", "before": "95790bf891e76fee5e1747ab589903a6a1f80f22", "after": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7", "ref": "refs/heads/master", "user_id": 4, "user_name": ...

Interface for dynamic objects in Typescript

I am currently using JavaScript to create an object and would like to include an interface for the data: JavaScript: const childGroups: Children = {}; childGroups.children = []; // Adding some data childGroups.children.push(children); Interface: ...

The appearance and functionality of the app undergo a noticeable transformation after being bundled with Webpack

After successfully migrating my Angular 2 project from SystemJS to Webpack using the latest version of Angular2-CLI, I noticed some unexpected changes in the design of the page. Despite minimal adjustments to the project files and Angular2 code during the ...

Tips on how to increase and update the index value by 2 within an ngFor loop while maintaining a fixed format

I have a specific template layout that displays only two items in each row as shown below. I want to use the ngFor directive to iterate through them: <div class="row" *ngFor="let item of cityCodes; let i = index"> <div class="col-6" (click)= ...

Aggregate the values in PostgreSQL from JSON data only if both values in a pair exist

Here is an example of how my JSON field appears: { "Ui": [ { "element": "TG1", "mention": "in", "time": 123 }, { "element": "TG1", "mention": "out", "time": 125 }, { "eleme ...

Transforming JSON into QGIS-compatible GeoJSON format can become quite complex when dealing with various features and data types

My current challenge involves retrieving JSON data from a specific API that is claimed to be in GeoJSON format. However, when attempting to read this data in QGIS, I encountered issues. To address this problem, I am looking to enhance my Python Script by ...

Validating JSON in C# using Regular Expressions

In the scenario that I am presented with a JSON string and need to validate it using C#, it is important to understand the structure of a JSON string. The format typically looks like this: string jsonStr = {"Id":123,"Value":"asdf","Time":"adf","isGood":fa ...

Decoding JSON files using Golang

Looking for a way to access the value of sha in a JSON structure using Golang? { "some text":[ { "sha":"1234567", "message":"hello world", "author":"varung", "timestamp":1479445228 } ] } Can you help me figure out the best a ...

Inject an asynchronous callback into the constructor of a class by leveraging TypeScript and Node with Passport integration

Currently, I am utilizing the passport-http authentication library. The issue at hand is that its documentation makes use of callbacks while my implementation involves TypeScript classes with async/await functionalities, thus causing uncertainty regarding ...

What is the process to generate a universal error page in Angular?

I have implemented a simple example in Angular 6 using a globalErrorHandler for error cases. I have also included a loader that runs after the login operation and before loading data into a table. Everything seems to be working fine, but I have encountered ...

Implementing Custom Font Awesome Icons in Your Angular Project

I recently upgraded to a fontawesome subscription with a paid plan and have successfully created some custom icons. Now, I'm looking to integrate these icons into my angular app. Here are the dependencies listed in my package.json file: "@fortawe ...

Output the JSON string retrieved from a specified URL

I'm currently working on using ajax to retrieve and parse JSON data from a specific URL. I am looking for assistance on how to store the parsed array into a variable. Any guidance or suggestions would be greatly appreciated. Thank you! function rvOff ...

In my current project, I am implementing a feature in Angular 6 to close a Bootstrap modal once the server successfully receives the necessary data

Here, I am working on creating the content for a CRUD component that saves data as needed. My goal is to make the modal disappear once the data is submitted. <div class="container"> <div class="table-wrapper"> <div class="table-ti ...

Is there a specific type of input that can cause an error when using PHP's json_encode function?

Every time I try to pass an unconventional $var to json_encode($var), it never seems to fail. It's able to deserialize some Objects in mysterious ways. I'm searching for a scenario where PHP encounters something that is not JSON serializable (if ...

Learn how to break down Angular 2 with Typescript in just 5 minutes by troubleshooting issues

I've been delving into the world of TypeScript and Angular 2 by following the guide at https://angular.io/guide/quickstart. After going through all the steps, I encountered some errors with the final step npm start. Here's what I got: Microsoft ...

operating efficiently even when producing an incorrect output type

Exploring Typescript for the first time on Codepen.io has left me puzzled. I'm unsure why, despite defining the function signature and return type with an interface, I am able to return a different type without encountering any errors. Is there somet ...