skip to Main Content

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.

2

Answers


  1. 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('-');
    }
    
    Login or Signup to reply.
  2. Here is my version of this script:

    function formatDate(date) {
      const inputDate = new Date(date);
      const year = inputDate.getFullYear();
      const month = ('0' + (inputDate.getMonth() + 1)).slice(-2);
      const day = ('0' + inputDate.getDate()).slice(-2);
      return `${year}-${month}-${day}`
    }
    

    But please note that is expecting that you will pass a string like ‘Jan. 02, 2023’ and it will return a string. If a detailed explanation is needed can provide as an update.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search