0

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

1

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)

| improve this answer | |
  • 1
    Thanks @Gortonington. But I am getting 2020-05-03 as output.As getMonth() is zero indexed I have added getMonth()+1.Which gave me the expected output. Will there be any effect when the month reaches to 11,12? – Harry Jun 4 at 18:28
  • @Harry Good catch! I completely forgot about it. There will be 0 effect on it in later months. It goes from 0-11, so adding 1 will always push it to the correct month. I am going to update my answer now. – Gortonington Jun 4 at 18:46
  • Okay. Thanks @Gortonington. – Harry Jun 4 at 18:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.