【问题标题】:Month missing in getting dates for year if date is not available in month如果月份中的日期不可用,则在获取年份日期时缺少月份
【发布时间】:2015-12-31 11:24:42
【问题描述】:

我正在尝试使用以下代码在提供的日期之后获取明年的日期

var dateArray = new Array();
dateArray.push(date);
for(var i=1;i<12;i++){
    dateArray.push(new Date(date.getFullYear(),date.getMonth()+i,date.getDate()));
}
console.log(dateArray)

如果我选择 1-28 之间的日期,它工作正常,但是当我选择任何下个月不可用的日期时,它会移到下个月。

这里应该发生的是我应该得到所选日期不可用的月份的最后一个日期

【问题讨论】:

  • I am trying to get the dates for next year after provided date。对不起,什么?你能提供一些预期的输入和输出吗?
  • 我提供输入日期

标签: javascript jquery datetime


【解决方案1】:

正如您所说,Date 对象类型通过增加月份来处理月份中的日期溢出。为了做你想做的事,你需要添加一个if 语句来检查日期是否正确,如果不正确则修复它。

var date = new Date(2015, 2, 30);

var dateArray = new Array();
dateArray.push(date);
for (var i = 1; i < 12; i++) {
  dateArray.push(new Date(date.getFullYear(), date.getMonth() + i, date.getDate()));

  // check if the day of the month is correct.
  // If it isn't, we know that it overflowed into the next month
  if(dateArray[i].getDate() !== date.getDate()) {
    // setting the day to 0 will set it to the last day of the previous month
    dateArray[i].setDate(0);
  }

}
console.log(dateArray)

【讨论】:

    【解决方案2】:

    如果你想获取特定月份和年份的最后一天

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

    【讨论】:

      猜你喜欢
      • 2021-12-16
      • 2017-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多