一切诡异的程序问题都是有原因的!今天是2014-7-29,注意这个日期,它是下面问题的根源!
先看代码
var b=new Date();
b.setFullYear(2014);
b.setMonth(1);
b.setDate(28);
alert(b.toLocaleString());//是2014年3月28,不是2014年2月28
奇怪,js不是用0-11表示1到12月吗?那我setMonth(1)应该是2月才对啊,我又试了下其他数值,setMonth(0)成功表示1月,setMonth(2)是3月,。。。就是除了setMonth(1)以外,其他都是正常的!
我有记得之前这段代码是没问题的啊,为什今天这么诡异!?
setMonth(<span style="font-family: monospace; font-size: 14px; line-height: 26px;">numMonth</span><span style="font-family: monospace; font-size: 14px; line-height: 26px;">[</span><span style="font-family: monospace; font-size: 14px; line-height: 26px;">,</span><span style="font-family: monospace; font-size: 14px; line-height: 26px;"> </span><span style="font-family: monospace; font-size: 14px; line-height: 26px;">dateVal</span>);如果省略后面的参数,系统会调用<span style="font-size: 14px; line-height: 26px;"><span style="font-family:Arial;">getDate获取日期,并使用得到的日期值设置了日期,那么当前系统日期是2014-7-29,</span></span><pre name="code" class="javascript" style="font-family: Arial;"><span style="font-family: Arial; font-size: 14px; line-height: 26px;">getDate的值是29,</span><pre name="code" class="javascript">b.setFullYear(2014);
b.setMonth(1,29);
<span style="font-family:Arial;">2014年2月不是闰年,那么月份自动往下延伸,变成了3月。</span>
<span style="font-family:Arial;"></span><p class="indent" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial; font-size: 14px; line-height: 26px;"> <strong>解决方法</strong>:</p><p class="indent" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial; font-size: 14px; line-height: 26px;"> 1.可以在setMonth之前先调用setDate()设置日期;
2 .<span style="font-family: Arial; font-size: 14px; line-height: 26px; white-space: pre; background-color: rgb(240, 240, 240);">setMonth(month, date);</span></p><p class="indent" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial; font-size: 14px; line-height: 26px;"><span style="font-family:Courier New;"><em> 3.dateObj</em> = <strong>new Date(</strong><em>year</em>, <em>month</em>, <em>date</em>[<strong>, </strong><em>hours</em>[<strong>, </strong><em>minutes</em>[<strong>,</strong><em>seconds</em>[<strong>,</strong><em>ms</em>]]]]<strong>)</strong> 的形式。
也可以使用setFullYear()同时设置年、月、日,即<strong>setFullYear(</strong><em>numYear</em>[<strong>,</strong> <em>numMonth</em>[<strong>,</strong> <em>numDate</em>]]<strong>)。</strong></span></p>
<pre name="code" class="javascript"> function calcDays(begin,end)
{
var b=new Date();
b.setFullYear(begin.substring(0,4));
b.setDate(begin.substring(8,10));
b.setMonth(begin.substring(5,7)*1-1);
var e=new Date();
e.setFullYear(end.substring(0,4));
e.setDate(end.substring(8,10));
e.setMonth(end.substring(5,7)*1-1);
var days=Math.floor((e.getTime()-b.getTime())/(24*60*60*1000));
return days;
}
alert(calcDays('2014-06-26','2014-08-31'))//计算错误,8月31日被解析成8月1日