Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

javascript - 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 (in Grey color).

Whenever current date selected is 31st date of any month. suppose 31 may 2017 I select i will set in a textfield. If I click on 2 june 2017 rather then setting textfield to 2 june 2017 it sets 2 July 2017 ?

please suggest whats wrong is going here.

Code snippet used as follows

var tempDate = new Date(current); //Suppose : current --> Wed May 31 16:09:00 UTC+0530 2017 
var dayOfMonth = parseInt(element.text(), 10); //Suppose : element.text() --> 2   
tempDate.setMonth(tempDate.getMonth() + (dayOfMonth > 15 ? -1 : 1)); //tempDate.getMonth() + (dayOfMonth > 15 ? -1 : 1) returns 10
tempDate.setDate(dayOfMonth);

//Output Expected : 02 June 2017 but it gives 02 July 2017

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = new Date(); 
tempDate.setMonth(tempDate.getMonth() + (dayOfMonth > 15 ? 1 : -1)); 
tempDate.setDate(dayOfMonth);
alert(tempDate)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...