Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading