Php 在Javascript中获取一个月的天数时出现问题

Php 在Javascript中获取一个月的天数时出现问题,php,javascript,date,calendar,Php,Javascript,Date,Calendar,我有一系列的年、月、开始日和结束日选择元素。。 年和月当然是可用的,但问题是要从中选择的所选月份的天数,作为开始日期 我在JS文件中使用这个 days=新日期(2010,4,0).getDate();//返回29,应该是30 问题出在哪里,我通过php cal_days_in_month(0,42010)确定了每个月的天数,它返回30 提前感谢:)我用。它有许多方便的日期函数。您的代码 new Date(2010, 4, 0) …是不正确的;它可能在某些实现中起作用,但在其他实现中不起作用。D

我有一系列的年、月、开始日和结束日选择元素。。 年和月当然是可用的,但问题是要从中选择的所选月份的天数,作为开始日期

我在JS文件中使用这个
days=新日期(2010,4,0).getDate();//返回29,应该是30

问题出在哪里,我通过php cal_days_in_month(0,42010)确定了每个月的天数,它返回30

提前感谢:)

我用。它有许多方便的日期函数。

您的代码

new Date(2010, 4, 0)

…是不正确的;它可能在某些实现中起作用,但在其他实现中不起作用。
Date
构造函数需要年、月、日、小时、分钟和秒(除了
year
month
之外的所有内容都是可选的,因为如果使用单参数构造函数,它假设从历元值开始算起,您给出的是一毫秒),月份是基于0的,而天是基于1的(是的,真的-嘿,我没有设计它)。因此,4月1日是新的日期(2010年3月1日)
0
=1月,
1
=2月,
2
=3月,
3
=4月),没有月日
0
(根据规范第15.9.1.5节,范围为1..31)。

在谷歌Chrome中,它只输出30:

document.write(天=新日期(2010,4,0).getDate())


如果您只接受以1为基础的日期,则一个小技巧将给出给定月份的天数:

function getDaysForMonth(m,y){
  var datebase = new Date(y,m,1); //nb: month = zerobased
  datebase.setDate(datebase.getDate()-1);
  return datebase.getDate();
}
让我们把它作为2月的一部分:

var feb2000 = getDaysForMonth(2,2000); //=> 29
var feb2004 = getDaysForMonth(2,2004); //=> 29
var feb2008 = getDaysForMonth(2,2008); //=> 29
var feb2010 = getDaysForMonth(2,2010); //=> 28
您可以为其创建Date.prototype方法:

Date.prototype.daysThisMonth = function(){
 var x = new Date(this.getFullYear(),this.getMonth()+1,1);
 x.setDate(x.getDate()-1);
 return x.getDate();
};
//usage
var d1 = new Date('2010/2/23').daysThisMonth() //=> 28
//nb new Date('2010/2/23') in your notation: new Date(2010,1,23)

请确保使用“下个月”作为参数,因为当日期为0时,它会向后移动:

new Date(2012, 1, 0); //returns Jan not Feb
如果这是您经常使用的,请创建一个函数

function getDaysOfMonth(year, month){
   return new Date(year, month+1, 0).getDate()
}

谢谢,但我没有真正理解你的意思!:),这里是我得到代码的地方:@Dewan:我的观点是
新日期(2010,4,0)
无效,可以返回任何内容。第三个值不能是
0
(根据规范,必须是
1
31
包括在内),这意味着你得到什么就得到什么,不能信任它。我不知道你在做什么,但新的日期('2010/04/23')。这里的daysthisnooth()=30;firefox 3.6.13/w firebug 1.6:新日期(2010,4,0)。getDate()=30