-1

i'm trying to convert gen. 02, 2023 date in 2023-01-02 but my function formatDate:

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;

    return [year, month, day].join('-');
}

doesn't seem to work properly. Can you help me out?

It looks like i receive just NaN-NaN-NaN as value.

1 Answers1

0

You used getMonth() method to get the month number, but the month number is zero-based. So, the month number for January is 0, not 1. You need to subtract 1 from the month number before you pass it to the formatDate() function.

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;

    return [year, month, day].join('-');
}
user1874594
  • 2,277
  • 1
  • 25
  • 49