Javascript and setMonth behaving unexpectedly

I am doing datObj.setMonth(1), but the month is being set to March? Isn't 1 supposed to be February? I'm using Chrome 79.

Here's part of code meant to parse dates such as YYYY-MM-DD HH:MM:SS (because safari can't do that natively)

var date = "2020-02-02 23:59:00"

        if (typeof date == 'string')
        {
            var dateParts = date.split(/[:-\s]+/);

            if (dateParts.length == 6)
            {
                dateObj = new Date();

                dateObj.setYear(dateParts[0]);
                var m = dateParts[1] - 1;
                console.log('m= ' + m);
                dateObj.setMonth(m);
                console.log('after setmonth, date= ' + dateObj);
                dateObj.setDate(dateParts[2]);
                dateObj.setHours(dateParts[3]);
                dateObj.setMinutes(dateParts[4]);
                dateObj.setSeconds(dateParts[5]);
            }
        }

console.log(dateObj);
alert(dateObj);

Upvotes: 0

Views: 35

Answers (2)

Bergi
Bergi

Reputation: 664528

Your problem, as you figured, is that you're setting the month while the day is still 30. While you could work around that by using setFullYear and pass year, month and day at once, you really should just construct the whole Date object with the right values in the first place:

dateObj = new Date(dateParts[0], dateParts[1]-1, dateParts[2], dateParts[3], dateParts[4], dateParts[5]);

or rather using UTC as the timezone:

dateObj = new Date(Date.UTC(dateParts[0], dateParts[1]-1, dateParts[2], dateParts[3], dateParts[4], dateParts[5]));

Upvotes: 1

Just figured this out before I submitted. Today is January 30th, 2020. I can't change the month to February, because there is no February 30th. So, the code breaks either on the 29th or the 30th day of the month.

In JavaScript, it is advisable to do

dateObj.setMonth(monthNum -1, dayNum)

to set the day and month at the same time to avoid this problem

Upvotes: 0

Related Questions