Search code examples
javascriptgetdate

Javascript Date Object Off by One Month


I understand that javascript counts the months starting from 0. However, I don't know how to account for this when getting a date in the future.

For example, when attempting to get the date for tomorrow, the following code returns everything correct except for the month (prints as next month):

const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const month =  ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

var today = new Date();
today.setUTCDate(today.getUTCDate()+1);

let newDate = weekday[today.getDay()] +' '+today.getDate()+' '+month[today.getDay()]+', '+ today.getFullYear();

console.log(newDate)


Solution

  • Just replace today.getDay() to today.getMonth()

    const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
    const month =  ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
    
    var today = new Date();
    today.setUTCDate(today.getUTCDate()+1);
    
    let newDate = weekday[today.getDay()] +' '+today.getDate()+' '+month[today.getMonth()]+', '+ today.getFullYear();
    
    console.log(newDate)