Search code examples
javascriptdatedate-formatting

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)?


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 that might be relevant depending on where the JavaScript is executed.

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