Skip to content Skip to sidebar Skip to footer

Setmonth() Setting Wrong Date In The Case Of 31st Day

I am facing very strange behavior of setMonth function of JS. On click of a image i am showing a calendar, having all days of current month and some next and previous month's date

Solution 1:

In javascript date object, Month is starting form 0, so if you want to generate any month, then do accordingly. Refer this url for Date: MDN Date

As your code , I think you made mistake at dayOfMonth > 15 ? 1 : -1

var dayOfMonth  = 13;
alert((dayOfMonth > 15 ? 1 : -1))
var tempDate = newDate(); 
tempDate.setMonth(tempDate.getMonth() + (dayOfMonth > 15 ? 1 : -1)); 
tempDate.setDate(dayOfMonth);
alert(tempDate)

Solution 2:

I think that is for the standard behavior of the operation when the month does not have the day (31) the operation take the next month that have that day

>var date = new Date('2018/10/31');
undefined
>date
Wed Oct 31 2018 00:00:00 GMT-0600 (hora estándar central)
>date.setMonth(date.getMonth() + 1);
1543644000000
>date
Sat Dec 01 2018 00:00:00 GMT-0600 (hora estándar central)

Post a Comment for "Setmonth() Setting Wrong Date In The Case Of 31st Day"