Change date format

Hi,

I have this function

let day = new Date("2005-03-01"); //YYYY-MM-DD
var end = new Date("2005-03-03");

while(day <= end){
    startDay = day.setDate(day.getDate() - 1);
    endDay = day.setDate(day.getDate() + 1);
    msg.payload= {
                    "startDay": startDay,
                    "endDay": endDay
                }
    node.send(msg);

    day = new Date( day.setDate(day.getDate() + 1) )
}

It outputs the following

Screenshot 2023-03-07 112843

how would it be possible to get the dates in DD-MM-YYYY format?

Where is it that you want to display the date in that format?

The startDay and endDay will need to go to a post request to a URL

{
    "userId": 6412,
    "startDay": "01-01-2023",
    "endDay": "02-01-2023"
}

OK, I believe you can use node-red-contrib-moment to do such things. Or you could do it in javascript using the Date functions to get the individual parts and build the string.

This will work


let date = new Date(startDay).toISOString().split('T')[0]
startDay = date.split('-')[2] + '-' + date.split('-')[1] + '-' + date.split('-')[0]

date = new Date(endDay).toISOString().split('T')[0]
endDay = date.split('-')[2] + '-' + date.split('-')[1] + '-' + date.split('-')[0]

gives

"28-02-2005"

or probably better

let day = new Date("2005-03-01"); //YYYY-MM-DD
let end = new Date("2005-03-03");

while(day <= end){
    let startDay = day.setDate(day.getDate() - 1);
    let endDay = day.setDate(day.getDate() + 1);
    msg.payload= {
                    "startDay": timeStampToDate(startDay),
                    "endDay": timeStampToDate(endDay)
                }
    node.send(msg);

    day = new Date( day.setDate(day.getDate() + 1) )
}

function timeStampToDate(timeStamp) {
   let date = new Date(timeStamp).toISOString().split('T')[0]

   return date.split('-')[2] + '-' + date.split('-')[1] + '-' + date.split('-')[0]
}
1 Like

Wow. Perfect.

Thanks,

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.