Home > front end >  How to convert a date from one type to another typescript
How to convert a date from one type to another typescript

Time:03-25

React with Typescript:

I have a date picker(mui v5) that requires date value to be in format "yyyy-MM-dd". However the api return a type Date on the format "2022-01-12T00:00:00.000 00:00"

Attention: There are many answers to create a string in that format but I need a Date without this it won't work with typescrit

CodePudding user response:

There are basically to ways to do this.

String manipulation

Just use the ISO 8601 string you already have and manipulate it using split() or substring() so that you only have the relevant portion of the string. Use this when you don't need to do any calculation/ further processing with the date.

toLocaleDateString()

Parse the string first by passing it to the Date() constructor then format it using toLocaleDateString() and the locale en-CA to yield the result you need. The advantage of this approach is that you could do some processing that involves the date before eventually converting it to string.

const strManipulationSplit = "2022-01-12T00:00:00.000 00:00".split("T")[0];
const strManipulationSubstring = "2022-01-12T00:00:00.000 00:00".substring(0, 10);
const usingDate = new Date("2022-01-12T00:00:00.000 00:00").toLocaleDateString('en-CA');

console.log(strManipulationSplit);
console.log(strManipulationSubstring);
console.log(usingDate);

CodePudding user response:

The conclusion is that it can't be solved through React or JS

If I do:

const strManipulationSplit = "2022-01-12T00:00:00.000 00:00".split("T")[0]; const strManipulationSubstring = "2022-01-12T00:00:00.000 00:00".substring(0, 10); const usingDate = new Date("2022-01-12T00:00:00.000 00:00");

the return will be like: "Tue Dec 28 2021 21:00:00 GMT-0300" not "yyyy-MM-dd"

So I changed the API to return the format "yyyy-MM-dd"

  • Related