【问题标题】:31 days in February in Date objectDate 对象中的 2 月 31 天
【发布时间】:2013-04-29 10:04:57
【问题描述】:

此代码应记录给定月份的所有天数:

var date = new Date(2012,2,1);
var thisMonth = date.getMonth();
while(date.getMonth()==thisMonth) { // 31 steps ???
    console.log(date.getMonth(),date.getDate());
    date.setDate(date.getDate()+1);
}

除二月外,每个月都运行良好。有什么想法吗?

【问题讨论】:

  • 二月份你使用什么索引......?? 1 或 2 ...??
  • 月份从 0 开始编入索引。请参阅 this fiddle

标签: javascript date


【解决方案1】:

注意月份参数是0-indexed,所以你的代码是关于March而不是February

The doc:

表示月份的整数值,从 0 开始表示一月到 12 月 11 日。

【讨论】:

  • 哦,天哪,我好像老了……对不起大家问了这么一个微不足道的问题。
【解决方案2】:

使用 new Date(2012,1,1); 月份是从零开始的 ;-)

【讨论】:

    【解决方案3】:

    这很有趣:

    new Date('2014-02-28'); // Fri Feb 28 2014 01:00:00 GMT+0100
    new Date('2014-02-29'); // Sat Mar 01 2014 01:00:00 GMT+0100
    new Date('2014-02-30'); // Sun Mar 02 2014 01:00:00 GMT+0100
    new Date('2014-02-31'); // Mon Mar 03 2014 01:00:00 GMT+0100
    new Date('2014-02-32'); // Invalid Date
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多