I’m getting a specific date from a request in short date format and I am trying to change to iso format with the Date()
constructor, but I want to change only the format, not the date. Is there a way in javascript to do this?
Request
const { data } = await axios.post(`${ur}`, body_object);
Response:
"ReceivedDate": "26/12/2022",
Format data
data.ReceivedDate = new Date();
console.log(data.ReceivedDate) // output: 2023-03-21T00:38:39.169Z
Expected output: 2022-12-26
2
Answers
The issue with your code is that you’re changing the
data.ReceivedDate
to a newDate
instead. Instead, you need to do a bit of parsing with the.split()
method to get the days, months, and years. From here, just put it in the format of full year-month-day. If all you need is the string, then this is sufficient. If you need the fullDate
object, then just pass it to thenew Date()
constructor.Also, it is generally a bad idea to change the response object, so you’ll want to create a different variable to hold it. Like this:
You can do something like this: