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

Why is getDay() and getMonth() returning wrong values

I’m trying to turn a date which I’m getting into date + 1 day and then format it in a specific way. The first part works, but when I want to format that new date, I’m actually getting a different date than what I have initially after the increase.

var customDate = '/Date(1643587200000)/'
var number = customDate.replace(/\D/g,'');
var plusDay = new Date(parseInt(number));
console.log(plusDay) // this is the date before the increase
plusDay.setDate(plusDay.getDate() + 1);
console.log(plusDay); // this is the date I want

//this is the part where things start going wrong
var d = plusDay.getDay();
console.log(d);
var m = plusDay.getMonth();
console.log(m);
var y = plusDay.getFullYear();
console.log(y);

let fDate = new Date(y, m, d);
let ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(fDate);
let mo = new Intl.DateTimeFormat('en', { month: 'long' }).format(fDate);
let da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(fDate);
console.log (mo + ' ' + da + ', ' + ye);

What am I doing wrong here and how do I fix it? Why is it that if I have 31. January 2022 (/Date(1643587200000)/) as customDate, the result is 2. February 2022 (+1 day), but when it’s 31. July 2021 (/Date(1627689600000)/), the resulting date is 31. July 2021 (-1 day)?

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 :

getDay returns the day of the week, not the day of the month. Replace it by getDate.

P.S. Also your code is not considering the timezone offset.

var customDate = '/Date(1643587200000)/'
var number = customDate.replace(/\D/g,'');
var plusDay = new Date(parseInt(number));
console.log(plusDay) // this is the date before the increase
plusDay.setDate(plusDay.getDate() + 1);
console.log(plusDay); // this is the date I want

//this is the part where things start going wrong
var d = plusDay.getDate(); // modified
console.log(d);
var m = plusDay.getMonth();
console.log(m);
var y = plusDay.getFullYear();
console.log(y);

let fDate = new Date(y, m, d);
let ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(fDate);
let mo = new Intl.DateTimeFormat('en', { month: 'long' }).format(fDate);
let da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(fDate);
console.log (mo + ' ' + da + ', ' + ye);
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