setMonth()在第31天的情况下设置了错误的日期 [英] setMonth() setting wrong date in the case of 31st day
问题描述
我正在面对JS的setMonth函数的非常奇怪的行为。
单击图像时,我正在显示日历,该日历具有当月的所有天以及下个月和上个月的某些日期(灰色)。
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).
无论何时当前选择的日期是任何月份的31号。假设2017年5月31日,我选择将在文本字段中设置。如果我单击2017年6月2日,而不是将文本字段设置为2017年6月2日,那么它将设置为2017年7月2日?
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.
使用如下代码段
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
推荐答案
在javascript日期对象中,月份以0开头,因此,如果要生成任何月份,请相应地执行。请将该日期作为网址: MDN日期
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
作为您的代码,我认为您在
dayOfMonth> 15时出错了? 1:-1
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)
这篇关于setMonth()在第31天的情况下设置了错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!