我正试图形成一个日期,这是3个月前的当前日期。我通过下面的代码得到当前月份

var currentDate = new Date();
var currentMonth = currentDate.getMonth()+1;

你能给我提供一个逻辑来计算和形成一个日期(date数据类型的对象),考虑到当月份是一月(1)时,日期前3个月将是十月(10)吗?


当前回答

d.setMonth在浏览器try中修改了本地时间

 const calcDate = (m) => {
    let date = new Date();
    let day = date.getDate();
    let month = date.getMonth() + 1;
    let year = date.getFullYear();
    let days = 0;

    if (m > 0) {
      for (let i = 1; i < m; i++) {
        month += 1;
        if (month > 12) {
          year += 1;
          month = 1;
        }
        days += new Date(year, month, 0).getDate();
      }
    } else {
      for (let i = m; i < 0; i++) {
        month -= 1;
        if (month < 1) {
          year -= 1;
          month = 12;
        }
        days -= new Date(year, month, 0).getDate();
      }
    }

    const newTime = date.getTime() + 3600 * 24 * 1000 * days;
    return new Date(newTime);
  };

calcDate(3)//+3 month

其他回答

直接放入变量中的“一行代码”(多行代码,便于阅读):

var oneMonthAgo = new Date(
    new Date().getFullYear(),
    new Date().getMonth() - 1, 
    new Date().getDate()
);

var d = new Date(); 文档。写(d + "<br/>"); d.setMonth(d.getMonth() - 6); document . write (d);

for (let monthOfYear = 0;monthOfYear < 12;monthOfYear + +) { const maxDate = new Date(); const minDate = new Date(); const max = maxDate.setMonth(maxDate.getMonth() - (monthOfYear - 1), 0); const min = maxDate.setMonth(minDate.getMonth() - (monthOfYear), 1); console.log('max: ',新的日期(max)); console.log('min: ', new Date(min)); }

这应该可以处理加法/减法,只需输入一个负数来做减法,一个正值来做加法。这也解决了月份交叉的问题。

function monthAdd(date, month) {
    var temp = date;
    temp = new Date(date.getFullYear(), date.getMonth(), 1);
    temp.setMonth(temp.getMonth() + (month + 1));
    temp.setDate(temp.getDate() - 1); 

    if (date.getDate() < temp.getDate()) { 
        temp.setDate(date.getDate()); 
    }

    return temp;    
}

已经有了一个优雅的答案,但我发现它很难读,所以我自己做了一个函数。出于我的目的,我不需要一个消极的结果,但它也不难修改。

    var subtractMonths = function (date1,date2) {
        if (date1-date2 <=0) {
            return 0;
        }
        var monthCount = 0;
        while (date1 > date2){
            monthCount++;
            date1.setMonth(date1.getMonth() -1);
        }
        return monthCount;
    }