[SalesForce] How to convert date to yyyy-mm-dd format using ssjs without timestamp

I am trying to convert the date to YYYY-MM-DD format using SSJS. But not able to do that. Getting NAN.

var day = new Date();
var prevDate = new Date();
yesDate.setDate(day.getDate()-1);
var test = (yesDate);

test gives me the yesterdays result but in different format. "Wed, 03 Jun 2020 09:28:53 GMT-06:00". How can i convert that to YYYY-MM-DD format without timestamp?

Thanks in advance

Best Answer

You should be able to use the following function to format it correctly:

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) 
        month = '0' + month;
    if (day.length < 2) 
        day = '0' + day;

    var formattedDate = year + '-' + month + '-' + day;
    return formattedDate
}

You will notice that for month, I use a + 1 to it, this is because Month is a 0 indexed value. Meaning Januaray is 0 and December is 11. So by adding 1 you push it to the correct numeric representation of that month.

You would just call it like this:

var day = new Date();
var prevDate = new Date();
prevDate.setDate(day.getDate()-1);
var test = formatDate(prevDate);

When you then output test it should come out as 2020-06-03. (assuming today is 2020-06-04)

Related Topic