使用 JavaScript 获取一个月中的天数:问题
我试图使用 JavaScript 获取一个月中的天数,但遇到了问题。我目前正在使用提到的解决方案 此处。
这是我的代码:
function getDays(month,year){
if(month=="" || year==""|| year=="--Select--"){
document. getElementById("days"). innerHTML ="";
return;
}
var months= new Array();
alert("Month in Function"+month);// To test.
alert("Year in function"+year);
months[0]="January";
months[1]="February";
months[2]="March";
months[3]="April";
months[4]="May";
months[5]="June";
months[6]="July";
months[7]="August";
months[8]="September";
months[9]="October";
months[10]="November";
months[11]="December";
var index=months.indexOf(month);
alert("Index used"+index);
var datebase = new Date(year,index,1); //nb: month = zerobased
datebase.setDate(datebase.getDate()-1);
// Also tried database=new Date(year, index, 0).getDate();
document.getElementById("days").innerHTML =datebase.getDate();// This value is skewed.
}
我得到了该月各天的奇怪值,例如,2012 年 4 月给了我 31 天,2011 年 3 月给了我 28 天。对我在这里可能搞砸的事情的任何帮助都会有帮助。
I'm trying to get the days of a month using JavaScript and face a problem. I'm currently using a solution mentioned here.
Here's my code :
function getDays(month,year){
if(month=="" || year==""|| year=="--Select--"){
document. getElementById("days"). innerHTML ="";
return;
}
var months= new Array();
alert("Month in Function"+month);// To test.
alert("Year in function"+year);
months[0]="January";
months[1]="February";
months[2]="March";
months[3]="April";
months[4]="May";
months[5]="June";
months[6]="July";
months[7]="August";
months[8]="September";
months[9]="October";
months[10]="November";
months[11]="December";
var index=months.indexOf(month);
alert("Index used"+index);
var datebase = new Date(year,index,1); //nb: month = zerobased
datebase.setDate(datebase.getDate()-1);
// Also tried database=new Date(year, index, 0).getDate();
document.getElementById("days").innerHTML =datebase.getDate();// This value is skewed.
}
I get weird values for the days of the month for example, April 2012 gives me 31 days and March 2011 gives me 28 days. Any help on what I could be messing up here would be helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在使用
new Date(year,index,1)
构建日期,例如,如果您传递"March"
,则会给出 3 月 1 日。然后减去一天即可得到 2 月 28 日。然后你说三月有28天。显然,这是一个错误的结论。您需要使用以下方式构建:
You're building the date using
new Date(year,index,1)
, which gives e.g. the 1st of March if you pass"March"
. You then subtract one day to get the 28st of February. Then you say that March has 28 days. This is a wrong conclusion, obviously.You'd need to build using:
几个月前,我必须做同样的事情 - 获取给定一年中一个月的天数。有很多解决方案,但我认为这是最短、最好的一种。
该函数有两个参数:
1 月和 11 日 - 12 月
尝试一下:
A few months ago I have to do the same thing - get the number of days that a month have in a given year. There are a lot of solutions, but the this one I think is the shortest and nicest one.
The function has two parameters:
January and 11 - December
Try it: