Home > Mobile >  Changing date value in object in Node
Changing date value in object in Node

Time:11-24

For example i have a get request which takes some data from mongo db:


const getAllContracts = async (req, res) => {
  const contracts = await Contract.find({});
  res.status(StatusCodes.OK).json({ contracts, count: contracts.length });
};

As response it sends:

{
    "contracts": [
        {
            "_id": "637cbd3279de1dd12dd7d2f9",
            "tenant": "Nazar",
            "manager": "Misha",
            "object": "Автовокзал",
            "price": 99,
            "area": 335,
            "status": "Активний",
            "activeFrom": "2022-11-16T00:00:00.000Z",
            "activeUntil": "2022-11-18T00:00:00.000Z",
            "createdBy": "6372c4bc0c02f9ccf3363fe0",
            "contractManualId": "321a",
            "contractReason": "IDK",
            "contractComment": "Vasya",
            "createdAt": "2022-11-22T12:14:42.248Z",
            "updatedAt": "2022-11-22T12:14:42.248Z",
            "__v": 0
        },
        {
            "_id": "637cbd4d79de1dd12dd7d2fc",
            "tenant": "Nazar1111",
            "manager": "Misha",
            "object": "Автовокзал",
            "price": 99,
            "area": 335,
            "status": "Активний",
            "activeFrom": "2022-11-16T00:00:00.000Z",
            "activeUntil": "2022-11-18T00:00:00.000Z",
            "createdBy": "6372c4bc0c02f9ccf3363fe0",
            "contractManualId": "321a",
            "contractReason": "IDK",
            "contractComment": "Vasya",
            "createdAt": "2022-11-22T12:15:09.755Z",
            "updatedAt": "2022-11-22T12:15:09.755Z",
            "__v": 0
        }
    ],
    "count": 2
}

I would like to change response date formats in activeFrom and activeUntil to dd-mm-yyyy but idk how to do that. For example 2022-11-16T00:00:00.000Z i want to change to 16.11.2022

CodePudding user response:

Simple answer: Loop over contracts and modify the properties

contracts.map((contract) => {
  const activeFromDate = new Date(contract.activeFrom);
  contract.activeFrom = formatDate(activeFromDate);

  const activeUntilDate = new Date(contract.activeUntil);
  contract.activeUntil = formatDate(activeUntilDate);
  return contract;
});
function formatDate(date) {
  // the  1 is because getMonth is zero-based.
  return `${date.getDate()}.${date.getMonth()   1}.${date.getFullYear()}`
}

But couple of thoughts:
1.) If you're passing this to UI code it would be "cleaner" for the UI to do this formatting.
2.) IF you have to do this on the backend return both the formatted and raw data rather than the inplace update like above. So same structure but instead of assigning to contract.activeFrom you should assign the resultant to contract.formattedActiveFrom and return both properties to the UI. That way if they need to do any additional tinkering with the date they have it available in a format that's easy to use.

  • Related