skip to Main Content

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


  1. The issue with your code is that you’re changing the data.ReceivedDate to a new Date 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 full Date object, then just pass it to the new 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:

    const data = {ReceivedDate: '26/12/2022'}; // example data
    
    const [days, months, year] = data.ReceivedDate.split('/');
    const isoString = `${year}-${months}-${days}`;
    console.log(isoString);
    Login or Signup to reply.
  2. You can do something like this:

    let ReceivedDate;
    ReceivedDate = "26/12/2022"
    
    const splitDate = ReceivedDate.split("/"); // ["26", "12", "2022"]
    ReceivedDate = splitDate[2] + "-" + splitDate[1] + "-" + splitDate[0];
    
    console.log(ReceivedDate)  // 2022-12-26
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search