JavaScript – Converting text variable to Date

Tags: , ,



Im working on a React project where im sending HTTP POST request to my API. Inside the API, my entity has a field which is type of DateTime (.NET).

In my React app though my date variable is a text. Example: let dateText = '18-03-2021'.

Im trying to figure out how can i take this text and make a Date type of variable which has a format that my API can process and take without causing an exception.

As far as the backend goes (.NET), i just need a date, hours do not matter since they are not stored in the database.

To be honest im not that much familiar with formatting dates in JS. What i’ve found on google didnt help me since it didnt convert it to my needed format. Is there any library that can help me, or can i somehow do it without one?

What i’ve tried is not much, but following:

let dateText = '18-3-2021'
1. let date = new Date(dateText) -> returns `Invalid date`
2. let date = Date.parse(dateText) -> returns `NaN`

I can maybe try to make a custom function that formats the date, but is this good practice?

EDIT: I just found out this format 03-18-2021 works but the one im trying to pass isnt: 18-03-2021. Which brings me to my question above the EDIT.

Answer

What i did is just make a custom function:

const formatDate = (date) =>{
    let parts = date.split('-');
    const day = parts[0];
    const month = parts[1];
    const year = parts[2];
    let formattedDate = month + '/' + day + '/' + year;
    return formattedDate;
}

Still not sure though if this is good practice, but that is how i achieved it.



Source: stackoverflow